操作另一个数组中的对象数组

Manipulate an array of objects inside another array

我在处理另一个对象数组时遇到问题 array.I 创建了一个示例来解释我的需要。所以这里我们有这个数组:

array1 =
[
    {
        "first": "A",
        "second": [
            "one"
        ]
    },
    {
        "first": "A",
        "second": [
            "three"
        ]
    },
    {
        "first": "C",
        "second": [
            "four"
        ]
    },
    {
        "first": "D",
        "second": [
            "one"
        ]
    },
    {
        "first": "C",
        "second": [
            "three"
        ]
    },
]

我一直在尝试创建一个逻辑来操作这个数组,return 像这样:

result = 
[
    {
        "first": "A",
        "second": [
            "one",
            "three"
        ]
    },
    {
        "first": "C",
        "second": [
            "three",
            "four"
        ]
    },
    {
        "first": "D",
        "second": [
            "one"
        ]
    },
]   
for(let i = 0, n = result.length; i < n; ++i) {

   for(let k = 0, l = result[i].second.length; k < l; ++k) {
  
     result[i].second.push("anything");
  
   }

 }

你能试试这个吗?

let result = [];

array1.forEach(obj => {
  if(!result[obj.first]) {
    result[obj.first] = {
      first: obj.first
      , second: []
    }
  }

  result[obj.first].second.push(obj.second[0])
})

您可以采用以下方法:

array1 =
[
    {
        "first": "A",
        "second": [
            "one"
        ]
    },
    {
        "first": "A",
        "second": [
            "three"
        ]
    },
    {
        "first": "C",
        "second": [
            "four"
        ]
    },
    {
        "first": "D",
        "second": [
            "one"
        ]
    },
    {
        "first": "C",
        "second": [
            "three"
        ]
    },
]

var array2 = []

array1.forEach(function(item) {
  var existing = array2.filter(function(v, i) {
    return v.first == item.first;
  });
  if (existing.length) {
    var existingIndex = array2.indexOf(existing[0]);
    array2[existingIndex].second = array2[existingIndex].second.concat(item.second);
  } else {
    if (typeof item.second == 'string')
      item.second = [item.second];
    array2.push(item);
  }
});

console.log(array2);