Javascript通过相同的对象键重新排列数组

问题描述 投票:1回答:5

是)我有的:

myArray = [ {type: "My Application"}, {type: "My Component"}, {color: ["red"] } ]

我需要的:

withUniqueKeys = [ {type: ["My Application", "My Component"] }, {color: ["red"]} ]

我将如何遍历myArray以获取类似withUniquKeys的数组?我一直在玩这个WAAAYYYY太久了。一个lodash解决方案也没关系。

javascript arrays loops object
5个回答
4
投票

你可以使用reduceObject.entries

let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: "red" } ]

let op = myArray.reduce((op,inp)=>{
  let [key,value] = Object.entries(inp)[0]
  op[key] = op[key] || []
  op[key].push(value)
  return op
},{})

// in case you want property with one value to be object only

let final = Object.entries(op)
           .map(([key,value]) => ( {[key]: value.length === 1 ? value[0] : value}))

console.log(final)

IMO最好让你的数据结构保持这样的一致性,因此它很容易用于以后的目的,否则你需要检查值是否只是一个字符串或数组而不是应用方法

let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: "red" } ]

let op = myArray.reduce((op,inp)=>{
  let [key,value] = Object.entries(inp)[0]
  op[key] = op[key] || []
  op[key].push(value)
  return op
},{})

console.log(op)

1
投票

你可以用Array.prototype.reduce()Object.entries()这样做:

const arr = [{type: "My Application"}, {type: "My Component"}, {color: "red" }];

const result = Object.entries(arr.reduce((acc, x) => {
  Object.entries(x).forEach(([k, v]) => {
    acc[k] = [...(acc[k] || []), v];
  });
  return acc;
}, {})).map(([k, v]) => ({ [k]: v.length > 1 ? v : v[0] }));

console.log(result);

1
投票

试试这个:

  1. 通过键减少初始数组以分组条目
  2. 将对象条目映射到相应对象的数组

let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: ["red"] } ]

myArray = myArray.reduce((acc, el) => {
  let prop = Object.keys(el)[0];
  if (!acc[prop]) acc[prop] = [el[prop]];
  else acc[prop].push(el[prop])
  return acc;
},{})

myArray = Object.keys(myArray).map(d => ({[d]:myArray[d].length ===1?myArray[d][0]:myArray[d]}));

console.log(myArray)

0
投票

首先,您可以使用Array.reduce()通过keys进行分组。然后,在第二步,您可以在生成的Array.map()上使用Object.entries()来获得所需的结构:

let myArray = [
  {type: "My Application", category: "game"},
  {type: "My Component", category: "other"},
  {color: "red" }
];

let res = myArray.reduce((acc, curr) =>
{
    Object.keys(curr).forEach(k =>
    {
        acc[k] = (acc[k] || []).concat(curr[k]);
    });
    return acc;
}, {});

res = Object.entries(res).map(([k, v]) => ({[k]: v.length > 1 ? v : v[0]}));

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

注意,如果输入对象有多对key/value,这种方法也会起作用。


0
投票

其他答案看起来很好,这里是一个简短的选择,也使用Array.reduceObject.entries

const myArray = [{type: "My Application"}, {type: "My Component"}, {color: "red"}];

const withUniqueKeys = Object.entries(
  myArray.reduce((result, item) => {
    const [key, val] = Object.entries(item)[0];
    result[key] = result[key] ? [...[result[key]], val] : val;
    return result;
  }, {})
).map(([key, val]) => ({[key]: val}));

console.log(withUniqueKeys);
© www.soinside.com 2019 - 2024. All rights reserved.