通过其中一个键将对象数组转换为单个对象

3

我正尝试将一个包含对象的数组转换为一个单独的对象,其中键是“page”,值是“has_access”。这样,我以后就可以通过例如has_access.about来访问它。

是否有一行代码可以实现这个功能?

我尝试过了这个,但它只返回原始数组。

var myData = Object.keys(data).map(key => {
    return data[key];
})

这是我想转换的源数组

[
    {
        "id": 215,
        "page": "home",
        "has_access": 1,
    },
    {
        "id": 216,
        "page": "about",
        "has_access": 0,
    },
    {
        "id": 217,
        "page": "profile",
        "has_access": 1,
    }
]

期望结果:

has_access: {
    home: 1
    about: 0
    profile: 1
}
4个回答

4

您可以使用.reduce()方法获取结果对象:

const data = [
    {"id": 215, "page": "home", "has_access": 1},
    {"id": 216, "page": "about", "has_access": 0},
    {"id": 217, "page": "profile", "has_access": 1}
];

const has_access = data.reduce((r, c) => (r[c.page] = c.has_access, r), {});

console.log(has_access);


1
你可以使用 reduce 循环遍历对象,并使用 Object.assign 更新累加器。

var data = [{"id":215,"page":"home","has_access":1},{"id":216,"page":"about","has_access":0},{"id":217,"page":"profile","has_access":1}];
var result = data.reduce((c, v) => Object.assign(c, {[v.page]: v.has_access}), {});

console.log(result);


0

This can be achieved with the reduce() method, via the following:

const array = [
    {
        "id": 215,
        "page": "home",
        "has_access": 1,
    },
    {
        "id": 216,
        "page": "about",
        "has_access": 0,
    },
    {
        "id": 217,
        "page": "profile",
        "has_access": 1,
    }
];

const result = array.reduce((acc, i) => ({ ...acc, [ i.page ] : i.has_access }), {});

console.log(result);


0
很简单 - 指定键和值,然后使用mapreduce:

const a = [{
    "id": 215,
    "page": "home",
    "has_access": 1
  },
  {
    "id": 216,
    "page": "about",
    "has_access": 0
  },
  {
    "id": 217,
    "page": "profile",
    "has_access": 1
  }
];

const value = "has_access";
const key = "page";

const res = {
  [value]: a.map(o => [o[key], o[value]]).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
}

console.log(res);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接