gpt4 book ai didi

javascript - 根据年龄值将对象数组拆分为新数组或对象

转载 作者:行者123 更新时间:2023-12-03 10:01:48 24 4
gpt4 key购买 nike

根据JavaScript中的年龄值将对象数组拆分为新数组或对象

var items = [
{name:"Foo", age:16, color:"w"},
{name:"Bar", age:18, color:"b"},
{name:"foo", age:16, color:"w"},
{name:"bar", age:18, color:"w"},
{name:"foobar", age:18, color:"b"},
{name:"barfoo", age:20, color:"w"}
];

如何返回类似以下的列表:
var items = [
{age:16,name:"Foo"|"foo",gender:"w"|"w"},
{age:18,name:"Bar"|"bar"|"foobar",gender:"b"|"w"|"b"},
{age:20,name:"barfoo",gender:"w"}
];

我已经工作了,但输出的名称中带有“undefined”。下面是我的代码。
var data = [{age: 21,name: "Walter",color: "black"},{age: 25,name: "sentinel",color: "black"
},{age: 21,name: "Micah",color: "purple"},{age: 25,name: "mike",color: "black"},{age: 21,name: "Danny",color: "white"},{age: 25,name: "mike",color: "black"}];
var obj=data;
var arrayobj = obj.length;
var i, row, arr = obj, ss = {};
for (i = 0; i < arr.length; i++) {
row = arr[i];
ss[row.age] = ss[row.age] || {count: 0};
if (ss[row.age][row.age] === undefined) {
ss[row.age][row.name] = row.name;
ss[row.age]['name']+=row.name+'|';
ss[row.age]['color']+=row.color+'|';
ss[row.age]['count'] += 1;
}
}
console.table(ss);

最佳答案

我假设您想按项目的年龄对其进行分组。这是一种方法:

(fiddle)

items.reduce(function(buckets,item){
if(!buckets[item.age]) buckets[item.age] = [];
buckets[item.age].push(item);
return buckets;
},{});

让我们解释一下:
  • 对于每个项目,如果我们还没有一个“bucket”,请创建一个新的空
  • 将其添加到存储桶中
  • 返回新的更新的存储桶列表。

  • 该方法返回一个具有3个属性的对象:16,18和20,每个属性都包含具有该年龄的对象。

    关于javascript - 根据年龄值将对象数组拆分为新数组或对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170069/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com