简体   繁体   English

如何比较对象数组中的对象值?

[英]How to compare object values in an array of objects?

I am trying to compare an array of objects.我正在尝试比较一组对象。 Each object has the same keys, but varying values for each key.每个对象都有相同的键,但每个键的值不同。 I would like to create a function that compares each object for similar key value pairs.我想创建一个函数来比较每个对象的相似键值对。

I only care about the quality and location keys for each object, and I want to compare all objects against these two keys.我只关心每个对象的质量和位置键,我想将所有对象与这两个键进行比较。

For example, if the first and second object in the array of objects contains the same value for two keys, I would like to create an output array of objects that summarizes each grouping.例如,如果对象数组中的第一个和第二个对象包含两个键的相同值,我想创建一个输出对象数组来总结每个分组。

Explanation: Object one and two contain the same value for quality and location .解释:对象一和对象二包含相同的qualitylocation值。 Since the third object does not, a new object should be created that summarizes the information from the first and second objects.由于第三个对象没有,因此应该创建一个新对象来汇总来自第一个和第二个对象的信息。 That new object should contains an array of all fruit names and and array of all tags.该新对象应包含所有水果名称的数组和所有标签的数组。 The output object is shown below.输出对象如下所示。

// Input
data = [
  {
    id: '1',
    fruit: 'granny smith',
    quality: 'good',
    location: 'chicago',
    tags: ['green', 'sweet'],
  },
  {
    id: '2',
    fruit: 'Fuji',
    quality: 'good',
    location: 'chicago',
    tags: ['red', 'tart'],
  },
  {
    id: '3',
    fruit: 'gala',
    quality: 'bad',
    location: 'san diego',
    tags: ['tall', 'thin'],
  },
];

// Function
function compareObjects(arr) {
  const grouped = [];

  // Loop over every fruit
  const similarObjects = arr.filter((obj, id) => {
    // create structure for each common object
    let shape = {
      id,
      fruits: [],
      quality: '',
      tags: [],
    };

    arr.forEach((item) => {
      // Return a new shape object that contains all fruit names, tags, and quality
      if (item.quality == obj.quality && item.location == obj.location) {
        shape.id = id;
        shape.fruits.push(item.fruit);
        shape.fruits.push(obj.fruit);
        shape.quality = item.quality;
        shape.tags.push(item.tag);
        shape.tags.push(obj.tag);
        return shape;
      }
    });
    return obj;
  });

  return similarObjects;
}

console.log(compareObjects(data));

// Output
const output = [
  {
    id: 'a',
    fruits: ['grann smith', 'fuji'],
    quality: 'good',
    tags: ['green', 'sweet', 'red', 'tart'],
  },
  ...
];


You can group the data by their quality and location using Array.prototype.reduce and filter the groups where the length is greater than one.您可以使用Array.prototype.reducequalitylocationdata进行分组,并过滤​​长度大于 1 的组。

 const data = [ { id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] }, { id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] }, { id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] }, ], output = Object.values( data.reduce((r, d) => { const key = `${d.quality}+${d.location}`; if (!r[key]) { r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] }; } r[key].fruits.push(d.fruit); r[key].tags.push(...d.tags); return r; }, {}) ).filter((d) => d.fruits.length > 1); console.log(output);

If you also wish to only keep unique fruits then you can map over the resultant array and remove the duplicates using a Set .如果您还希望只保留唯一的水果,那么您可以映射结果数组并使用Set删除重复项。

 const data = [ { id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] }, { id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] }, { id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] }, ], output = Object.values( data.reduce((r, d) => { const key = `${d.quality}+${d.location}`; if (!r[key]) { r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] }; } r[key].fruits.push(d.fruit); r[key].tags.push(...d.tags); return r; }, {}) ) .filter((d) => d.fruits.length > 1) .map((d) => ({ ...d, fruits: [...new Set(d.fruits)] })); console.log(output);

Other relevant documentations:其他相关文件:

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

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