0

I have an array of keys and I want to iterate of them and return their corresponding values.

Generally, I know, I can just do a object.key_name or object[key_name] but I have a dynamic array and will populate with different keys.

Data:

data = [{hello: 'abc', asd: '123', fgh: '345' }, 
{hello: 'sdf', asd: '456', fgh: 'df' }, 
{hello: 'ty', asd: '789', fgh: '345675' },
{hello: 'qwe', asd: '123', fgh: '987' }]

array format: arr = ['asd', 'fgh']

I am trying to do: let x = data.map(o => arr.map(strs => o[strs]));

Result:

["123", "345"]
["456", "df"]
["789", "345675"]
["123", "987"]

Is there any way for me to get:

["123", "456", "789", "123"]  <= array for asd
["345", "df", "345675", "987"] <= array for fgh

2 Answers 2

2

Change the order of your map calls - first iterate the format array, and then extract the values from the data:

const data = [{"hello":"abc","asd":"123","fgh":"345"},{"hello":"sdf","asd":"456","fgh":"df"},{"hello":"ty","asd":"789","fgh":"345675"},{"hello":"qwe","asd":"123","fgh":"987"}]

const format = ['asd', 'fgh']

const result = format.map(f => data.map(o => o[f]))

console.log(result)

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

Comments

0

You where almost there! You just need to start with the array of the keys:

arr.map(key => data.map(o => o[key]));

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.