合并2个数组的对象

时间:2018-05-05 07:47:14

标签: javascript arrays json angular

让我们看一个例子。

let arr1 = [{image: "some_image_url_1.png"}, {image: "some_image_url_2.png"}]

let arr2 = [{value: "some value 1"}, {value: "some value 2"}]

我需要合并这2个对象数组并创建以下数组。

let result = [{image: "some_image_url_1.png", value: "some value 1"}, {image: "some_image_url_2.png", value: "some value 2"}]

对于角度2,有没有解决方案呢?也许用lodash?

8 个答案:

答案 0 :(得分:1)

要从现有阵列生成新阵列,您可以使用map()

let arr1 = [{image: "some_image_url_1.png"}, {image: "some_image_url_2.png"}]

let arr2 = [{value: "some value 1"}, {value: "some value 2"}]

let result = arr1.map(function(i, idx){
  var obj = {};
  obj.image = i.image; 
  obj.value = arr2[idx].value;
  return obj;
});

console.log(result)
[{image: "some_image_url_1.png", value: "some value 1"},
{image: "some_image_url_2.png", value: "some value 2"}]

答案 1 :(得分:0)

如果您乐意修改arr1中的实际对象,您可以做一些简单的事情,例如:

arr1.forEach((item, i) => item.value = arr2[i].value)

如果您不想修改原始数组,可以使用Object.assign构建新对象:

arr1.map((item, i) => Object.assign({}, item, arr2[i]))

答案 2 :(得分:0)

使用javascript地图功能。

var arr1 = [1, 2, 3]
var arr2 = ['a', 'b', 'c']

var result = arr1.map(function(e, i) {
  return [e, arr2[i]];
});

请参阅map

答案 3 :(得分:0)

使用Object.assign实现此目的,您不需要依赖于value对象的密钥名称。您可以在属性名称上更灵活地使用代码:

let arr1 = [{image: "some_image_url_1.png"}, {image: "some_image_url_2.png"}]

let arr2 = [{value: "some value 1"}, {value: "some value 2"}]

let res = [];
arr1.forEach(function(obj, index){
  let newObj = Object.assign(obj, arr2[index])
  res.push(newObj);
});

console.log(res);

使用Object.assign的主要优点是它允许您将对象与多个属性合并,如:

let arr1 = [{image: "some_image_url_1.png"}, {image: "some_image_url_2.png"}]

let arr2 = [{value: "some value 1", anotherValue: 'anotherValue1'}, {value: "some value 2",  anotherValue: 'anotherValue2'}]

let res = [];
arr1.forEach(function(obj, index){
  let newObj = Object.assign(obj, arr2[index])
  res.push(newObj);
});

console.log(res);

答案 4 :(得分:0)

对于任意数组的数组和不等长度,您可以减少数组和对象的Object.assign

{uri: "path/to/image"}

答案 5 :(得分:0)

Angular使用打字稿和箭头符号。你只需要一行:

func getSingleValue(_ value: String?..., seperator: String = " ") -> String? {

    return value.reduce("") {
    ($0) + seperator + ($1 ?? "")
    }.trimmingCharacters(in: CharacterSet(charactersIn: seperator) )
}

答案 6 :(得分:0)

您可以合并两个数组而无需删除重复项:

使用解构的ES6

const arr1 = [{image: "some_image_url_1.png"}, {image: "some_image_url_2.png"}];
const arr2 = [{value: "some value 1"}, {value: "some value 2"}]
const arr3 = [...arr1, ...arr2];

使用concat的ES5

const arr1 = [{image: "some_image_url_1.png"}, {image: "some_image_url_2.png"}];
const arr2 = [{value: "some value 1"}, {value: "some value 2"}];
arr2.concat(arr1);

答案 7 :(得分:0)

它应该像这样工作:

let arr1 = [{image: "some_image_url_1.png"}, {image: "some_image_url_2.png"}]
let arr2 = [{value: "some value 1"}, {value: "some value 2"}]
let merged = arr1.concat(arr2);