【问题标题】:looping through javascript objects循环遍历 javascript 对象
【发布时间】:2017-05-12 10:26:56
【问题描述】:

我有一个包含许多对象的数组(所有这些数据都将通过 ajax 调用来,例如假设只有 3 条记录)。

data : [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];

有什么方法可以遍历整个数组并找到具有相同 id 的对象并将它们的名称连接起来并过滤数组以使其像这样

data : [{name : "a,c",id : "100"},{name : "b",id:"101"}]

谢谢

【问题讨论】:

标签: javascript jquery arrays object filter


【解决方案1】:

您可以使用forEach() 循环并检查 id 是否存在并将名称连接到该值。

var data = [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];
var result = []

data.forEach(function(e) {
  //Check if property with current object id exists in object provided as thisArg param and if it doesn't exists set its value to current object and push it to result array
  if(!this[e.id]) this[e.id] = e, result.push(this[e.id])
  // if it does exists then concat name of current object to name of existing one that had the same id
  else this[e.id].name += ',' + e.name
}, Object.create(null))

console.log(result)

【讨论】:

  • 感谢 Nenad。非常感谢。
  • 我建议解释一下它是如何工作的。代码很好,但解释真的会有所帮助。特别是使用this 和空白对象的棘手之处。 (旁注:注意与Object.prototype 的命名冲突,我建议使用Object.create(null),而不是{};或者如果使用ES2015+,请使用Map。)
【解决方案2】:

我建议使用哈希表,作为回调函数的闭包。如果散列存在与否,则遍历对象和对象。如果存在,则将名称添加到对象的 name 属性中,否则使用实际数据创建一个新对象并将其推送到结果集中。

返回Array#reduce中的临时数组。

var data = [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];


data = data.reduce(function (hash) {
    return function (r, a) {
        if (hash[a.id]) {
            hash[a.id].name += ',' + a.name;
        } else {
            hash[a.id] = { name: a.name, id: a.id };
            r.push(hash[a.id]);
        }
        return r;
    };
}(Object.create(null)), []);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 2013-03-09
    • 2015-09-16
    • 1970-01-01
    • 2016-07-08
    • 2015-10-15
    • 2011-04-18
    相关资源
    最近更新 更多