0

I have two arrays:

[{Name: "Jack", Depot: "5"}, {Name: "Jill", Depot: "6"}]

and

[{Depot Name: "Edgware"}, {Depot Name: "Romford"}]

I need to take the objects from the second array and merge them with the objects in the first array to produce a result of:

[{Name: "Jack", Depot: "5", Depot Name: "Edgware"}, {Name: "Jill", Depot: "6", Depot Name: "Romford"}]

Any help with this would be much appreciated

4
  • 1
    firstly the key needs to be 'Depot Name' Commented Sep 9, 2016 at 15:17
  • Can you show us what you tried? Commented Sep 9, 2016 at 15:18
  • @BeeNag This is not a get code for free site. Please try it yourself first. Commented Sep 9, 2016 at 15:18
  • 3
    arr1.map((o, i) => Object.assign({}, o, arr2[i])) Commented Sep 9, 2016 at 15:18

2 Answers 2

7

var array1 = [{
  Name: "Jack",
  Depot: "5"
}, {
  Name: "Jill",
  Depot: "6"
}];
var array2 = [{
  'Depot Name': "Edgware"
}, {
  'Depot Name': "Romford"
}];

for (var a in array1) {
  for (var p in array1[a]) {
    //to esclude all possible internal properties
    if (array1[a].hasOwnProperty(p)) {
	 array2[a][p] = array1[a][p];
    }
  }
}

console.log(array2);

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

3 Comments

Add an .hasOwnProperty() check to your solution and it's good.
Why? Explain me please.
There is the possibility of internal properties. You're right.
1

Here is a solution with Object.assign().

P.S: Check for browser compatibility, this solution might not work in IE

var arr1 = [{
  "Name": "Jack",
  "Depot": "5"
}, {
  "Name": "Jill",
  "Depot": "6"
}];

var arr2 = [{
  "Depot Name": "Edgware"
}, {
  "Depot Name": "Romford"
}];

var arr1Copy = arr1;
var newArr = arr1Copy.map(function(v, i) {
  return Object.assign(v, arr2[i]);
});

console.log(newArr);

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.