使用javascript创建具有多个属性的对象数组

时间:2018-04-19 14:25:41

标签: javascript arrays

如何创建具有两个属性nameshade的对象数组?

[{
    "name": "black",
    "shade": "dark"
  }, {
    "name": "white",
    "shade": "light"
  },
  {
    "name": "red",
    "shade": "dark"
  }, {
    "name": "blue",
    "shade": "dark"
  },
  {
    "name": "yellow",
    "shade": "light"
  }
]

我现在有两个不同的阵列。

name = ["black","white","red","blue","yellow"]
shade = ["dark","light","dark","dark","light"]

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:3)

使用map

var output = name.map( (s, i) => ({name : s, shade : shade[i]}) );

<强>演示

var name1 = ["black","white","red","blue","yellow"];

var shade = ["dark","light","dark","dark","light"];

var output = name1.map( (s, i) => ({name : s, shade : shade[i]}) );

console.log( output );

答案 1 :(得分:1)

您可以使用.map()

let names = ["black", "white", "red", "blue", "yellow"],
    shades = ["dark", "light", "dark", "dark", "light"];

let merge = (a1, a2) => names.map((n, i) => ({name: n, shade: shades[i]}));

console.log(merge(names, shades));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

您可以使用辅助对象来解决类型。

var names = [ "black", "white", "red", "blue", "yellow"],
    shades = ["dark", "light", "dark", "dark", "light"],
    temp = { name: names, shade: shades },
    result = Object
        .keys(temp)
        .reduce(
            (r, k) => (temp[k].forEach((v, i) => (r[i] = r[i] || {})[k] = v), r),
            []
        );

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

答案 3 :(得分:0)

var new_array = [];
// assuming the arrays have the same length
for (var i = 0; i < name.length; i++)
    new_array.push({name: name[i], shade: shade[i]});