0

so i have this kind of array

columnData:[
 {
   title: 'Male Members',
   key: 'm_members'
 }
 {
   title: 'Female Members',
   key: 'f_members'
 }
]

and i want to turn it into something like this

newColumn: {
  m_members: 'Male Members',
  f_members: 'Female Members
}

how to do that with javascript or with lodash?

4 Answers 4

1

You can loop through the items with the forEach method then fill a new object with the key and value obtained from columnData:

const columnData = [{title: 'Male Members',key: 'm_members'},{title: 'Female Members',key: 'f_members'}]

let newData = {};
columnData.forEach(e => {
  newData[e.key] = e.title
})

console.log(newData)

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

1 Comment

wow this is the most simple approach that even me a beginner on the array thing can quickly understand
1

Use Array.reduce and Object.assign

var columnData = [{title: 'Male Members',key: 'm_members'},{title:'Female Members',key: 'f_members'}];
newColumn = columnData.reduce((a,{title, key}) => Object.assign(a, {[key]:title}),{});
console.log(newColumn);

Comments

1

You can do this with Object.assign and spread syntax ....

const data = [{title: 'Male Members',key: 'm_members'}, {title: 'Female Members',key: 'f_members'}]

const result = Object.assign({}, ...data.map(({title, key}) => ({[key]: title})));
console.log(result)

Comments

0
const result = {};

for(const {title, key} of columnData)
  result[key] = title;

A simple for loop does it.

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.