根据其他键值获取数组中出现的次数

IT技术 javascript reactjs lodash
2021-05-05 07:28:49
var json = [{
        "city": "California",
        "name": "Joe",
        "age": 17,
        "type",:"custom"
    }, {
        "city": "California",
        "name": "Bob",
        "age": 17,
        "type",:"predefined"
    }, {
        "city": "California",
        "name": "Bob",
        "age": 35,
        "type",:"custom"
    }, {
        "city": "Texas",
        "name": "Bob",
        "age": 35,
        "type",:"custom"
    }, {
        "city": "Florida",
        "name": "Bob",
        "age": 35,
        "type",:"predefined"
 }];

我有上面的数组,我必须构造对象,基于“类型”值,即“预定义”或“自定义”,如下所示

updatedjson = {
    "predefined": [{
            "name": "California",
            "count": 1
        }, {
            "name": "Florida",
            "count": 1
        }]
     "custom": [{
            "name": "California",
            "count": 2
        }, {
            "name": "Texas",
            "count": 1
        }]
 }

任何使用 javascript 或 lodash 的方法

3个回答

使用 Lodash

var json = [{
  "city": "California",
  "name": "Joe",
  "age": 17,
  "type": "custom"
}, {
  "city": "California",
  "name": "Bob",
  "age": 17,
  "type": "predefined"
}, {
  "city": "California",
  "name": "Bob",
  "age": 35,
  "type": "custom"
}, {
  "city": "Texas",
  "name": "Bob",
  "age": 35,
  "type": "custom"
}, {
  "city": "Florida",
  "name": "Bob",
  "age": 35,
  "type": "predefined"
}];

// Solution to the problem

var updatedJson = _(json).groupBy("type").value();    // #1

_.forOwn(updatedJson, function(value, key) {
  let countByCity = _(value).countBy('city').value(); // #2
  let res = [];

  _.forOwn(countByCity, function(value, key) {
    res.push({                                        // #3
      name: key,
      count: value
    });
  });

  updatedJson[key] = res;
});

console.log(updatedJson);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

解释

  1. 代码首先按类型分组
  2. 然后按城市计数,在组内
  3. 最后以预期的格式将计数对象推送到数组中

你可以使用reduce&findIndex

var json = [{
  "city": "California",
  "name": "Joe",
  "age": 17,
  "type": "custom"
}, {
  "city": "California",
  "name": "Bob",
  "age": 17,
  "type": "predefined"
}, {
  "city": "California",
  "name": "Bob",
  "age": 35,
  "type": "custom"
}, {
  "city": "Texas",
  "name": "Bob",
  "age": 35,
  "type": "custom"
}, {
  "city": "Florida",
  "name": "Bob",
  "age": 35,
  "type": "predefined"
}];

var updatedjson = json.reduce(function(result, item) {
  // check if type is present in the object
  // if not present then add a key by name custom/predefined
  if (!result[item.type]) {
    result[item.type] = [];
    // add city name and intial count
    result[item.type].push({
      name: item.city,
      count: 1
    })
  } else {
    // now find the index of the object whe name matches with current city
    let m = result[item.type].findIndex(function(obj) {
      return obj.name === item.city
    })
    // if no matches then add the new object to either custom/predefined
    if (m === -1) {
      result[item.type].push({
        name: item.city,
        count: 1
      })
    } else {
      // if matches then increase the value of count
      result[item.type][m].count += 1
    }

  }
  return result;

}, {});

console.log(updatedjson)

您可以使用array.reduce使用聚合数据创建一个新对象。例子:

  const result = json.reduce((obj, data) => {
      // if this is a new type, we must initialize it as an empty array and push the first record.
      if(!obj[data.type]) {
        obj[data.type] = [];
        obj[data.type].push({name: data.city, count: 1});
        return obj;
      }
      // else ... check if the current city is present in that type
      const existingRecord = obj[data.type].find(d => d.name === data.city);
      if(!existingRecord) {
         // if the city is not present in that type, we initialize it with count 1
         obj[data.type].push({name: data.city, count: 1});
         return obj;
      }
      // if the city is present, we just update count = count + 1;
      existingRecord.count++;
      return obj;
    }, { })

现在,您可能希望将其中一些逻辑提取到单独的函数中以提高可读性。我认为你不需要 lodash,但如果你已经将它包含在你的项目中,那么可以随意使用它:P