如何合并数组和对象

时间:2017-08-03 16:08:03

标签: javascript arrays object

var data =[{
    "name": "jack",
    "age": 10
  }, {
    "name": "jhon",
    "age": 12
  }];
var obje = {"name":{'data_one':0,'data_two':5},"age":{'data_one':8,'data_two':9}};

如何从此数组和对象中获得以下结果。

 data[{"name":{"data_one":0,"data_two":5,"display_name":"jack"}
    "age":{"data_one":8,"data_two":9,"display_name":10}},
    {"name":{"data_one":0,"data_two":5,"display_name":"jhon"}
    "age":{"data_one":8,"data_two":9,"display_name":12}}]

3 个答案:

答案 0 :(得分:0)

您可以使用Object.assign

的嵌套方法



var data = [{ name: "jack", age: 10 }, { name: "jhon", age: 12 }],
    object = { name: { data_one: 0, data_two: 5 }, age: { data_one: 8, data_two: 9 } },
    result = data.map(o => Object.keys(o).reduce((r, k) =>
        Object.assign(r, {
            [k]: Object.assign({}, object[k], { display_name: o[k] })
        }), {}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

Javascript对象是属性的集合,属性是名称(或键)与值之间的关联。

您可以拥有如下对象(请记住键值对)

spices = [{"name":"pasilla", "spiciness":"mild"},
          {"name":"jalapeno", "spiciness":"hot hot hot!"},
          {"name":"habanero", "spiciness":"LAVA HOT!!"}];

更多详情:Javascript object documentation

答案 2 :(得分:-1)

只需使用在Array原型中声明的push。

data.push(obje)