简体   繁体   中英

Converting an array of objects into a single object by one of the keys

I am trying to convert an array that contains objects into a single object where the key is "page" and the value is "has_access". So I could access it later with has_access.about for example.

Is there a single one line of code that could achieve this?

I tried this but it is giving me back the original array.

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

Here is the source array that I would like to convert

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

Desired result:

has_access: {
    home: 1
    about: 0
    profile: 1
}

You can get the resultant object using .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); 

You can use reduce to loop thru the object and use Object.assign to update the accumulator,

 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); 

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); 

It's easy - specify the key and the value, then use map and reduce :

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM