在JavaScript中将几个数组组合成一个对象数组

时间:2017-04-05 13:59:09

标签: javascript arrays reduce accumulator

假设我有三个数组,描述了一些名字,阅读的书籍数量以及[名字]中这些人的真棒程度:

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

我试图使用.reduce()将它们组合在一起来创建一个包含每个数组中相关索引的对象数组,但我失败了:

    let people = [
    {
       name: "Mary",
       noOfBooks: 2,
       awesomeness: "pretty cool"
    },
    {
       name: "Joe",
       noOfBooks: 1,
       awesomeness: "meh"
    },
    {
       name: "Kenan",
       noOfBooks: 4,
       awesomeness: "super-reader"
    }
  ]

我也通过减少获得了它:

let arrFinal = [];

 names.reduce(function(all, item, index) {
  arrFinal.push({
    name: item,
    noOfBooks: numberOfBooks[index],
    awesomeness: awesomenessLevel[index]
  })
}, []);

3 个答案:

答案 0 :(得分:6)

您可以使用<TreeView ... ItemTemplate="{StaticResource HQTemplate}" 执行此操作,如下所示:

map

&#13;
&#13;
let result = names.map( (v, i) => ({
    name: names[i], 
    noOfBooks: numberOfBooks[i],
    awesomenessLevel: awesomenessLevel[i]
}));
&#13;
let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

let result = names.map( (v, i) => ({
    name: names[i], 
    noOfBooks: numberOfBooks[i],
    awesomenessLevel: awesomenessLevel[i]
}));

console.log(result);
&#13;
&#13;
&#13;

在这种情况下,

.as-console-wrapper { max-height: 100% !important; top: 0; }map效果更好,因为 names 数组(或其他两个)中的元素数量与输出中所需的元素数。在这种情况下,使用reduce更为自然。

答案 1 :(得分:5)

使用map在输入数组和输出数组之间创建一对一映射。

let people = names.map(function (e, i) {
    return {name:e, noOfBooks:numberOfBooks[i],awesomeness: awesomenessLevel[i]};
});

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

let people = names.map(function (e, i) {
    return {name:e, noOfBooks:numberOfBooks[i],awesomeness: awesomenessLevel[i]};
});


console.log(people);

答案 2 :(得分:1)

您可以通过将所有数组合并到一个对象并使用键名作为数组中结果对象的属性名来使用动态方法

df.replace(stop,regex=True,inplace=True)
let names = ["Mary", "Joe", "Kenan"],
    numberOfBooks = [2, 1, 4],
    awesomenessLevel = ["pretty cool", "meh", "super-reader"],
    object = { name: names, noOfBooks: numberOfBooks, awesomeness: awesomenessLevel },
    result = Object.keys(object).reduce((r, k) =>
        (object[k].forEach((a, i) =>
            (r[i] = r[i] || {})[k] = a), r), []);

console.log(result);