将对象键值分组到具有相同结构的新对象

Group object key values to a new object with same structure

我有这个 JSON 并且我需要按键分组一个新对象:

[
    {
        "product": "name 1",
        "price": "3000",
        "inspection": false,
    },
    {
        "product": "name 2",
        "price": "1000",
        "inspection": true,
    },
    {
        "product": "name 3",
        "price": "5000",
        "inspection": false,
    },
]

预期最终结果:

    {
        "product": ["name 1", "name 2", "name 3"],
        "price": ["3000", "1000", "5000"],
        "inspection": [false, true, false]
    }

我尝试使用 -> for, foreach <- 但没有得到 good/optimum 结果。我也考虑过使用 reduce 但我无法让它工作。

   const jsonList = [
        {
            "product": "name 1",
            "price": "3000",
            "inspection": false,
        },
        {
            "product": "name 2",
            "price": "1000",
            "inspection": true,
        },
        {
            "product": "name 3",
            "price": "5000",
            "inspection": false,
        },]
    
    const convertedJson = jsonList.reduce((acc, item) => {
        acc.product.push(item.product);
        acc.price.push(item.price);
        acc.inspection.push(item.inspection);
    }, {product: [], price: [], inspection: []})

您可以使用array.reduce这种方式来解决您的问题

rows = [
  { product: 'name 1', price: '3000', inspection: false },
  { product: 'name 2', price: '1000', inspection: true },
  { product: 'name 3', price: '5000', inspection: false }
]

这应该有效:

{
    "product"   : rows.map( r => r.product ),
    "price"     : rows.map( r => r.price ),
    "inspection": rows.map( r => r.inspection )
}

对于任何形状的对象,这将在任何键下对项目进行分组:

const arr = [
  { product: "name 1", price: 3000, inspection: false },
  { product: "name 2", price: 1000, inspection: true },
  { product: "name 3", price: 5000, inspection: false },
]

const groups = arr.reduce((groups, obj) =>
  Object.entries(obj).reduce((groups, [key, val]) => (
    { ...groups, [key]: (groups[key]??[]).concat(val) }
  ), groups)
, {})

console.log(groups)

可以通过按键过滤 Object.entries(obj) 的结果来更改分组的键。

const first = [
    {
        "product": "name 1",
        "price": "3000",
        "inspection": false,
    },
    {
        "product": "name 2",
        "price": "1000",
        "inspection": true,
    },
    {
        "product": "name 3",
        "price": "5000",
        "inspection": false,
    },
];

const result = {};
first.map(obj=>{
  for([key,val] of Object.entries(obj)){
    if(result[key]){
      result[key].push(val);
    }else {
      result[key] = [] ;
      result[key].push(val);
    }
    
  }
})
console.log(result)

let data = [
    {
        "product": "name 1",
        "price": "3000",
        "inspection": false,
    },
    {
        "product": "name 2",
        "price": "1000",
        "inspection": true,
    },
    {
        "product": "name 3",
        "price": "5000",
        "inspection": false,
    },
];

let output = Object.fromEntries(
  Object.keys(data[0]).map(k => 
    [k, data.map(d => d[k])]
  )
);

console.log(output);

下面介绍的是实现所需 objective.

的一种可能方法

代码段

// one possible method to transform given array
const myTransform = arr => (
  arr.reduce(
    (acc, { product, price, inspection }) => (
      (acc.product ??= []).push(product),
      (acc.price ??= []).push(name),
      (acc.inspection ??= []).push(inspection),
      acc
    ),
    {}
  )
);

// using a simple for loop:
const myTransform2 = arr => {
  // initialize result "res" as empty object
  const res = {};
  
  // iterate over each elt in array "arr"
  for ({ product, price, inspection } of arr) {
    // if res has no key product, add one with value as empty array
    // push the "product" to the above key
    (res.product ??= []).push(product);
    // same logic for price
    (res.price ??= []).push(name);
    // same for inspection
    (res.inspection ??= []).push(inspection);
  };
  // return the result
  return res;
};

const dataArr = [{
    "product": "name 1",
    "price": "3000",
    "inspection": false,
  },
  {
    "product": "name 2",
    "price": "1000",
    "inspection": true,
  },
  {
    "product": "name 3",
    "price": "5000",
    "inspection": false,
  },
];

console.log(
  'transformed array:\n',
  myTransform(dataArr)
);

console.log(
  'transformed array using for loop:\n',
  myTransform2(dataArr)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

说明

添加到上面代码段的评论。