【问题标题】:Merge objects into array将对象合并到数组中
【发布时间】:2022-01-06 19:40:05
【问题描述】:

我想将多个与 test 具有相同 id 的对象转换为对象数组

实际:

const array= [
    { "test": 1},
    { "test": 2},
 { "test": 3},
 { "test": 4},
]

预期:

test: [1,2,3,4]

有人可以帮忙

【问题讨论】:

  • 你尝试过什么,到底有什么问题?
  • 你试试array.map(e => e.test)

标签: javascript arrays reactjs react-native


【解决方案1】:

只需像这样使用本机方法映射(阅读更多herehere):

const array= [
  { "test": 1},
  { "test": 2},
  { "test": 3},
  { "test": 4},
];
const newArray = array.map(p => p.test);
console.log(JSON.stringify(newArray)); //[1,2,3,4]

希望这会有所帮助.. ;D

【讨论】:

    【解决方案2】:

    您可以为此https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map 使用地图功能:

    const newarray = array.map(x => x.test);
    console.log(newarray);
    

    【讨论】:

      【解决方案3】:
      const result = {};
      
      yourArray.forEach( ( object ) => {
        const keys = Object.keys( object );
        for ( let i = 0; i < keys.length; i++ ) {
           const key = keys[ i ];
           if ( ! key in result ) { 
              result[ key ] = [];
           }
           result[key] = [...result[key], ...object[key] ];
        }
      });
      
      console.log( result );
      

      在这种情况下:

      1. 您需要在数组中进行迭代
      2. 每次迭代都有一个新对象
      3. 从那里迭代当前对象的所有键
      4. 如果结果中不存在该键,则创建一个新的空数组
      5. 将结果中的值与对象的当前值合并。
      6. 值存储在结果中。

      【讨论】:

        【解决方案4】:

        您可以映射对象中的值。

        const
            array = [{ test: 1 }, { test: 2 }, { test: 3 }, { test: 4 }],
            values = array.flatMap(Object.values);
        
        console.log(values);

        【讨论】:

          【解决方案5】:

          const arr = [
            { "test": 1 },
            { "test": 2 },
            { "test": 3 },
            { "test": 4 },
            { "test1": 1 },
            { "test1": 5 },
            { "test2": 6 }
          ];
          const newArr = arr.reduce((acc, cur) => ({
              ...acc, 
              [Object.keys(cur)[0]]: (acc[Object.keys(cur)[0]] || []).concat(Object.values(cur)[0])
          }), {});
          
          console.log( newArr );
          //{ "test": [1,2,3,4], "test1": [1,5], "test2": [6] }

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-10-25
            • 2019-08-15
            • 2022-07-22
            • 1970-01-01
            • 1970-01-01
            • 2021-12-14
            • 2023-01-11
            • 2019-05-07
            相关资源
            最近更新 更多