0

An example will speak for itself :

Array of Object :

[{ 
    userId: 'ab4e3870-287e-11e7-b5a1-abb6183e9866',
    email: '[email protected]' 
},{ 
    userId: 'ae149220-2883-11e7-bbf9-1fb134f2b4ad',
    email: '[email protected]' 
}]

Object

{ 
    'ab4e3870-287e-11e7-b5a1-abb6183e9866': { name: 'john', roles: 'detective'},
    'ae149220-2883-11e7-bbf9-1fb134f2b4ad': { name: 'james', roles: 'plumber'}, 
}

The result i'd like would be :

[{ 
    userId: 'ab4e3870-287e-11e7-b5a1-abb6183e9866',
    email: '[email protected]',
    name: 'john', 
    roles: 'detective' 
},{ 
    userId: 'ae149220-2883-11e7-bbf9-1fb134f2b4ad',
    email: '[email protected]',
    name: 'james', 
    roles: 'plumber' 
}]

So basically, the value of the key that match the userId in Object is added to that object in the array.

Is there some simple way I don't see to do that? Without external libraries in ES6?

1
  • Of course, just iterate through the array and the object keys and check whether the array object has a userId equal to the other object's key Commented Apr 24, 2017 at 1:58

1 Answer 1

1
var data = [{ 
    userId: 'ab4e3870-287e-11e7-b5a1-abb6183e9866',
    email: '[email protected]' 
},{ 
    userId: 'ae149220-2883-11e7-bbf9-1fb134f2b4ad',
    email: '[email protected]' 
}]

var d = { 
    'ab4e3870-287e-11e7-b5a1-abb6183e9866': { name: 'john', roles: 'detective'},
    'ae149220-2883-11e7-bbf9-1fb134f2b4ad': { name: 'james', roles: 'plumber'}, 
};

Using ES6 spread operator ...

data = data.map(function(item) {
  return {...item, ...d[item.userId]}
});

ES5: By adding properties manually

data = data.map(function(item) {
  item.name = d[item.userId].name;
  item.roles = d[item.userId].roles;
  return item;
});
Sign up to request clarification or add additional context in comments.

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.