Liga
Liga

Reputation: 3439

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
}

Upvotes: 3

Views: 61

Answers (4)

Jack Bashford
Jack Bashford

Reputation: 44087

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

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30360

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

Upvotes: 0

Eddie
Eddie

Reputation: 26844

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

Upvotes: 1

Mohammad Usman
Mohammad Usman

Reputation: 39322

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

Upvotes: 4

Related Questions