【问题标题】:Javascript Rearrange array by same object keyJavascript通过相同的对象键重新排列数组
【发布时间】:2019-04-05 18:21:17
【问题描述】:

我有什么:

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

我需要什么:

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

我将如何遍历 myArray 以获取像 withUniquKeys 这样的数组?我玩这个 WAAAYYYY 太久了。 lodash 解决方案也可以。

【问题讨论】:

  • 您是否只有 typecolor 或不同和/或更多属性?

标签: javascript arrays loops object


【解决方案1】:

您可以使用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)

【讨论】:

  • 如果只有一个值(例如color),显然 OP 不想要数组。
  • @Jeto 也针对这种情况进行了更新,但 IMO 最好有一个一致的结构
【解决方案2】:

您可以像这样使用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);

【讨论】:

    【解决方案3】:

    试试这个:

    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)

    【讨论】:

      【解决方案4】:

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

      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,这种方法也可以工作。

      【讨论】:

        【解决方案5】:

        其他答案看起来不错,这是一个简短的替代方案,也使用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);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-11
          相关资源
          最近更新 更多