Reputation: 1508
Hi here i am having an array,
const JSON_PAGES = ['my-needs','a-bit-about-me','my-home','my-income']
and an object like this
const columnsFromBackend = {
"my-needs": {
name: "my-needs",
items: [{ name: "Dhanush", age: 24 }]
},
"a-bit-about-me": {
name: "a-bit-about-me",
items: [{ name: "Dharma", age: 24 }]
},
"my-home": {
name: "my-home",
items: [{ name: "Sachin", age: 24 }]
},
"my-income": {
name: "my-income",
items: [{ name: "Kumar", age: 24 }]
}
};
In the above array i.e JSON_PAGES whose values are present as a key inside the above mentioned object i.e columnsFromBackend.
i need to extract the items value from the object by using the JSON_PAGES array values. Like this
result:
let myneeds = [{ name: "Dhanush", age: 24 }];
let abitaboutme = [{ name: "Dharma", age: 24 }]
let myhome = [{ name: "Sachin", age: 24 }]
let myincome = [{ name: "Kumar", age: 24 }]
For referencing i have added the extracted values in a variable. Is there any way i can compare the array with the object and get the required value. Please help me with that.
Thanks in advance
Upvotes: 1
Views: 252
Reputation: 3231
If you want to put the results into an array,
You can get the values to look for by using Object.values(columnsFromBackend)
, then filter()
the items and finally use map()
on the result to return an array with the output you want.
const JSON_PAGES = ['my-needs','a-bit-about-me','my-home','my-income']
const columnsFromBackend = {
"my-needs": {
name: "my-needs",
items: [{ name: "Dhanush", age: 24 }]
},
"a-bit-about-me": {
name: "a-bit-about-me",
items: [{ name: "Dharma", age: 24 }]
},
"my-home": {
name: "my-home",
items: [{ name: "Sachin", age: 24 }]
},
"my-income": {
name: "my-income",
items: [{ name: "Kumar", age: 24 }]
}
};
const res = Object.values(columnsFromBackend).filter(item => JSON_PAGES.includes(item.name)).map(({ items }) => items);
console.log(res)
Upvotes: 1
Reputation: 11
let values = JSON_PAGES.map((page) => columnsFromBackend[page].items)
let [my_need,abitaboutme,myhome,myincome] = values;
Upvotes: 1