1

I have have two arrays, I want to merge them into one object. I have given some examples of what I have and what I want to achieve. I tried _.union and few other underscore methods.

var original = [
  {
    Country: 'US',
    value: '10'
  },
  {
    Country: 'Turkey',
    value: '5'
  }
];

var newlist =["Afghanistan", "Antarctica","Turkey"]

The Results I want:

var results= [
  {
    Country: 'Afghanistan',
    value: '0'
  },
  {
    Country: 'Antarctica',
    value: '0'
  },
  {
    Country: 'Turkey',
    value: '5'
  }
];

The US would not appear in the final results because the newlist doesn't have US. So basically all the values from the new list would appear in the results with the values from the original list.

5
  • 1
    Have you tried writing some code? Commented Apr 7, 2017 at 2:36
  • tried _.union, but it attaches the last list to the first one. This is not what I want. I found that you could do .merge but underscore doesn't have merge. Commented Apr 7, 2017 at 2:38
  • if you would to merge both array where is the object with Country: 'US' in your expected output? Commented Apr 7, 2017 at 2:39
  • The US would not appear in the final resutls because the newlist doesn't have US. So basically all the values from the new list would appear in the results with the values from the original list. Commented Apr 7, 2017 at 2:42
  • Probably should add the above comment to the question - it's pretty vital. Commented Apr 7, 2017 at 3:01

1 Answer 1

5

A non-Underscore solution, that .map()s the new array, returning the object from the original array if it can .find() it, otherwise returning a new object:

var original = [
  { Country: 'US', value: '10' },
  { Country: 'Turkey', value: '5' }
];

var newlist =["Afghanistan", "Antarctica","Turkey"]

var result = newlist.map(function(v) {
  return original.find(function(o) { return o.Country === v })
      || { Country: v, value: '0' }
})

console.log(result)

It's a one-liner with ES6 arrow functions:

var original = [
  { Country: 'US', value: '10' },
  { Country: 'Turkey', value: '5' }
];

var newlist =["Afghanistan", "Antarctica","Turkey"]

var result = newlist.map(v => original.find(o => o.Country===v) || {Country:v, value:'0'})

console.log(result)

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.