3

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
}

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.