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

时间:2013-11-24 01:34:57

标签: javascript arrays

根据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);

3 个答案:

答案 0 :(得分:8)

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

fiddle

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

我们来解释一下:

  • 对于每件商品,如果我们还没有“桶”,请创建一个新的空桶
  • 将其添加到存储桶
  • 返回新的更新的存储桶列表。

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

答案 1 :(得分:1)

这会奏效。输出的格式与 exebook 提供的格式不同。

请检查并确认。 Here's a fiddle....

** UX Manager

var buckets = [];

for (var item in items) {
    var currentAge = items[item].age;

    if(!buckets[currentAge]) {
        buckets[currentAge] = [];
        for (var i in items) {      
            if (currentAge === items[i].age) {
                buckets[currentAge].push(items[i]);
            }
        }
    }

}

答案 2 :(得分:0)

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 result = [] // THIS IS THE RESULTING ARRAY THAT YOU WANT

function find(age) {
    for (var i = 0; i < result.length; i++)
        if (result[i].age == age) return i
    return -1
}

function append(i, obj) {
    result[i].name.push(obj.name)
    result[i].color.push(obj.color)
}

for (var i = 0; i < items.length; i++) {
    var x = find(items[i].age)
    if (x < 0) result.push({ age: items[i].age, name: [items[i].name], color : [items[i].color]})
    else append(x, items[i])
}

console.log(result) // PRINT THE RESULT, alternatively you can use alert(result)

输出

[ { age: 16, name: [ 'Foo', 'foo' ], color: [ 'w', 'w' ] },
  { age: 18, name: [ 'Bar', 'bar', 'foobar' ], color: [ 'b', 'w', 'b' ] },
  { age: 20, name: [ 'barfoo' ], color: [ 'w' ] } ]