0

I am trying to figure out how to take an array of two objects and merge them into a single object.

First off, here's what I did to produce my combined array from two arrays:

let p;
let v;
let combinedArray = [];

for (let diff of differences) {
  for (let mapping of mappings) {
    if (diff.path[0] === mapping.rhs) {
      p = diff.path[0];
      v = diff.rhs;
      combinedArray.push({ p, v });
    }
  }
}

The resulting combined array looks like this:

[ { p: 'prop_1', v: 'x1' },
  { p: 'prop_2', v: 'x2' } ]

What I need to do next is create a final object that looks like this:

{ 'prop_1': 'x1', 'prop_2': 'x2' }

How can I do that from the results of my "combined" array above? And, by the way, if there's a simpler way to do this from the outset of my initial two arrays I'm all for it. Open to suggestions here.

3
  • 3
    So why not replace combinedArray.push({ p, v }); with combinedObject[p] = v? Commented Jul 13, 2019 at 12:26
  • you forget to provide differences and mappings Commented Jul 13, 2019 at 12:27
  • @trincot, that makes a lot of sense. That really reduces the coded needed to produce the same result. Commented Jul 13, 2019 at 12:33

2 Answers 2

2

I would skip creating the combinedArray and go immediately for the target object structure. Replace:

combinedArray.push({ p, v }); 

with:

combinedObject[p] = v

Obviously you would initialise combinedObject as {}.

Now if you really want to convert combinedArray to a plain object, then Object.fromEntries is your friend:

const combinedArray = [{ p: 'prop_1', v: 'x1' }, { p: 'prop_2', v: 'x2' }];
  
const combinedObject = Object.fromEntries(combinedArray.map(({p, v}) => [p, v]));

console.log(combinedObject);

It would have been easier if your combinedArray already consisted of pairs. So you would have done combinedArray.push([p, v]). In that case you only need Object.fromEntries(combinedArray).

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

1 Comment

Thanks, the first of these two options works perfectly, and is definitely the most succinct of the options available to produce the result I need in this situation.
2

change your combinedArray to object and use like this

combinedArray[p] = v 

in case you need both the structures you can use reduce and destructuring further on your current output

let data = [ { p: 'prop_1', v: 'x1' },
  { p: 'prop_2', v: 'x2' } ]
  
let final = data.reduce((op,{p,v}) => {
  op[p] = v
  return op
},{})

console.log(final)

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.