遍历对象数组,查找匹配值,然后创建包含每组匹配值的新数组

时间:2017-02-22 23:56:11

标签: javascript arrays

我的问题可能没什么意义,但是我试图循环遍历可能引用或不引用相同项目/位置的对象数组。

每个地方都有一个唯一的标识符,所以我可以用它来检查。

现在我有原始数组以及在程序评估标识符时填充的新数组。

如果程序还没有在数组中看到该标识符,我希望在第二个数组中创建一个数组,并将该对象添加到新创建的数组中。

但是,如果之前已经看过该标识符,则应将该对象添加为匹配的数组中的下一个项目。

以下是一些示例数据

[{
    boro: "MANHATTAN",
    id: "0001"
    date: "2016-10-26T00:00:00",
    dba: "abc"
  }, {
    boro: "MANHATTAN",
    id: "0001"
    date: "2016-10-26T00:00:00",
    dba: "abc"
  },
  {
    boro: "MANHATTAN",
    id: "0200"
    date: "2016-10-26T00:00:00",
    dba: "abc"
  },
  {
    boro: "MANHATTAN",
    id: "0203"
    date: "2016-10-26T00:00:00",
    dba: "abc"
  }
]

程序应循环遍历数组,查看第一个对象的id,实现它不存在于新数组中,并将其添加为包含第一个对象的数组本身。然后第二个对象匹配该id,因此它被添加为第二个数组中第一个数组项的第二个数组项。

这是我尝试的开始

function findDups (arr){
    let newArray = []

    arr.forEach(function(current){
        if(newArray.indexOf(current.id) === -1){
            newArray.push([current.id{current}])
            console.log(newArray)
        }

    })

}

基本上,如何将整个对象动态添加为数组中的数组项

这基本上是我期待按ID分组的数组:

newArray = [
        [0001: [{
                    boro: "MANHATTAN",
                    id: "0001"
                    date: "2016-10-26T00:00:00",
                    dba: "abc"
                }, {
                    boro: "MANHATTAN",
                    id: "0001"
                    date: "2016-10-26T00:00:00",
                    dba: "abc"
                }

            ]

        ],
        0200: [{
            boro: "MANHATTAN",
            id: "0200"
            date: "2016-10-26T00:00:00",
            dba: "abc"
        }]
        etc. etc.
    ]

2 个答案:

答案 0 :(得分:2)

注意:您想要的输出不是有效的结构。我的代码生成了一个对象!

使用reduce创建ID的哈希对象,如下所示:



function groupById(arr) {
  return arr.reduce(function(h, o) { // for each object o in the array arr
    if(h[o.id]) h[o.id].push(o);     // if there is already an array for the id o.id, then push this object to it
    else h[o.id] = [o];              // if not, then create an array that contain this object o
    return h;
  }, {});
}


var array = [{"boro":"MANHATTAN","id":"0001","date":"2016-10-26T00:00:00","dba":"abc"},{"boro":"MANHATTAN","id":"0001","date":"2016-10-26T00:00:00","dba":"abc"},{"boro":"MANHATTAN","id":"0200","date":"2016-10-26T00:00:00","dba":"abc"},{"boro":"MANHATTAN","id":"0203","date":"2016-10-26T00:00:00","dba":"abc"}];

console.log(groupById(array));




答案 1 :(得分:0)

也许这可能就是你要找的东西?

var newArr = {};
var arr = [
  {
    boro: "MANHATTAN",
    id: "0001",
    date: "2016-10-26T00:00:00",
    dba: "abc"
  }, 
  {
    boro: "MANHATTAN",
    id: "0001",
    date: "2016-10-26T00:00:00",
    dba: "abc"
  },
  {
    boro: "MANHATTAN",
    id: "0200",
    date: "2016-10-26T00:00:00",
    dba: "abc"
  },
  {
    boro: "MANHATTAN",
    id: "0203",
    date: "2016-10-26T00:00:00",
    dba: "abc"
  }
];

function makeNewArrById (obj, i) {
  if(!newArr[obj.id]) {
    newArr[obj.id] = [];
  }

  newArr[obj.id].push(obj);
}

arr.map(makeNewArrById);

console.log(newArr);