1

I have an array of objects like this

const values = [{
    existing_value: 'Headline 56',
    new_value: 'Headline_new56',
  },
  {
    existing_value: 'Headline 59',
    new_value: 'Headline_new59',
  },
]

And I want to convert into this form.

const newObject = { "Headline 56": "Headline_new56",  "Headline 59": "Headline_new59"}

I was thinking something like this could work

const newObject = {}

const testvalues = values.map(obj => Object.assign( newObject, obj.existing_value: obj.new_value)) 

Syntactically it's not quite right. What is the best way to go about it?

3 Answers 3

4

Object.fromEntries is a possible approach

const values = [{
    existing_value: 'Headline 56',
    new_value: 'Headline_new56',
  },
  {
    existing_value: 'Headline 59',
    new_value: 'Headline_new59',
  },
]

const newObj = Object.fromEntries(values.map(({existing_value,new_value})=>[existing_value,new_value]))

console.log(newObj)

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

Comments

1

Use Array reduce

const values = [{
    existing_value: 'Headline 56',
    new_value: 'Headline_new56',
  },
  {
    existing_value: 'Headline 59',
    new_value: 'Headline_new59',
  },
];

const obj = values.reduce((a, b) => ({ ...a,
  [b.existing_value]: b.new_value
}), {})

console.log(obj)

Comments

0

Extracted from mozilla webdocs

const values = [{
        existing_value: 'Headline 56',
        new_value: 'Headline_new56',
    },
    {
        existing_value: 'Headline 59',
        new_value: 'Headline_new59',
    },
];

const newObj = values.map((obj) => {
    var rObj = {};
    rObj[obj.existing_value] = obj.new_value;
    return rObj;
});

console.log(newObj);

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.