Rey
Rey

Reputation: 1433

Produce Object from Array of Two Objects

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.

Upvotes: 0

Views: 54

Answers (2)

trincot
trincot

Reputation: 350272

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).

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

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)

Upvotes: 2

Related Questions