1

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

9
  • You need the results in separate variables? Commented Jun 18, 2020 at 16:09
  • just extracting values also ok Commented Jun 18, 2020 at 16:10
  • 1
    The variable names are not valid. A variable may not contain the - character. Commented Jun 18, 2020 at 16:11
  • thanks..i have edited Commented Jun 18, 2020 at 16:12
  • 2
    Why do you need to extract the values into variables? Can't you use the columnsFromBackend directly? For example columnsFromBackend["my-needs"].items. Commented Jun 18, 2020 at 16:15

2 Answers 2

1

let values = JSON_PAGES.map((page) => columnsFromBackend[page].items)
let [my_need,abitaboutme,myhome,myincome] = values;

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

Comments

1

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)

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.