简体   繁体   English

如何根据数组的值将数组对象转换/过滤为新的json对象?

[英]How can I transform/filter an array object into an new json object based on it's values?

I have one object array like this: 我有一个这样的对象数组:

[{id: 1, name: 'foo', sport: 'soccer'},
{id: 2, name: 'bar', sport: 'basketball'},
{id: 3, name: 'acme', sport: 'basketball'},
{id: 4, name: 'xyz', sport: 'baseball'}]

How can I transform this array of objects into an new javascript object that is filtered by the sport value ? 如何将对象数组转换为由sport值过滤的新javascript对象? Something like this: 像这样:

{
    soccer: [{id: 1, name: 'foo'}],
    basketball: [{id: 2, name: 'bar'},{id: 3, name: 'acme'}],
    baseball: [{id: 4, name: 'xyz'}]
}

Try this: 尝试这个:

var test = [{id: 1, name: 'foo', sport: 'soccer'},
{id: 2, name: 'bar', sport: 'basketball'},
{id: 3, name: 'acme', sport: 'basketball'},
{id: 4, name: 'xyz', sport: 'baseball'}];

test.reduce(function(aggregator, item) {

    if(!aggregator[item.sport]) {
        aggregator[item.sport] = [];
    }

    aggregator[item.sport].push({id: item.id, name: item.name})

    return aggregator;

}, {});

You could use Array.prototype.reduce() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce 您可以使用Array.prototype.reduce() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Something like this: 像这样:

array.reduce(function (accumulator, currentValue) {
  var sport = currentValue.sport;
  delete currentValue.sport;
  accumulator[sport] = accumulator[sport] || [];
  accumulator[sport].push(currentValue)
  return accumulator;
}, {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM