【问题标题】:Object.assign() , merge/overwrite keys, to copy the values of an array to create an objectObject.assign() ,合并/覆盖键,复制数组的值以创建对象
【发布时间】:2019-03-02 03:06:02
【问题描述】:

我曾经有一个包含一个对象的数组,如下所示: var myObj = [{'key': {an object}}];

我将它转换成这样的对象: Object.assign({}, ...myobj)

得到这个:{'key': [{an object}]}

问题是,在myobj 现在我有两个项目,具有相同的 KEY,如下所示:

[{'key': {an object}}, {'key': {another object}}]

如果我执行相同的Object.assign,我得到的结果是一个对象,里面有两个其他对象,这是正常的:{'key': {an object}}, {'key': {another object}}

问题是我可以将我的myobj 转换为那个结构吗:

{'key': [{an object}, {another object}]}

【问题讨论】:

  • 您当然可以编写代码来做到这一点。但使用Object.assign 并不能很好地自动使用。
  • let newObj = { key: myObj.map(o => Object.assign({}, o.key)) };
  • "如果我执行相同的 Object.assign 得到的结果是一个对象,其中包含另外两个对象,"。实际上不,你得到一个带有单个键的对象,其中包含共享该键的最后一个对象,所以{'key': {another object}}
  • 我建议你使用 lodash,你可以使用_.groupBy(_.flatMap(arr, _.entries), 0)。如果您需要有关 lodash 的详细答案来解释这一点,请告诉我

标签: javascript arrays object ecmascript-6 spread-syntax


【解决方案1】:

你可以使用Array.map():

const data = [{'key': 'an object'}, {'key': 'another object'}];

const result = {
  key: data.map(o => o.key)
};

console.log(result);

【讨论】:

    【解决方案2】:

    您可以通过遍历对象的条目并用数组替换值来手动合并对象。这是一个合并函数的示例,您可以使用两个参数,或在 reduce 中使用:

    const mergeObjects = (obj1, obj2) => 
      [...Object.entries(obj1), ...Object.entries(obj2)].reduce(
        (merged, [k, v]) => Object.assign(
          merged,
          { [k]: (merged[k] || []).concat(v) }
        ),
        {}
      );
    
    console.log(mergeObjects({ key: "a"}, { key: "b" }));
    console.log(
      [
        { key: "a", test: "b" }, { key: "c" }, { key: "d" } 
      ].reduce(mergeObjects)
    );

    【讨论】:

      【解决方案3】:

      您可以通过在第一级使用相同的键来合并对象。

      function merge(...objects) {
          return objects.reduce((a, b) => {
              Object.entries(b).forEach(([k, v]) => {
                  if (!(k in a)) {
                      return a[k] = v;
                  }
                  if (!Array.isArray(a[k])) {
                      a[k] = [a[k]];
                  }
                  a[k].push(v);
              });
              return a;
          }, {});
      }
          
      console.log(merge({ key: { foo: 'bar' } }, { key: { foo: 'baz' } }));
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案4】:
        const finalObj = {};
        const myObj =  [{'key': { obj : "hello"}}, {'key': { obj : "hello"}}, {'key2': {obj : "world"}}, {'key3': {obj : "world"}}];
        
        for( const oj of myObj) {
          const key = Object.keys(oj)[0];
        
          if(finalObj[key]){
             const tempArray =[].concat(finalObj[key]);
             tempArray.push(oj[key]);
             finalObj[key] = tempArray         
          }else{
           finalObj[key] = oj[key];
          }
        
        }
        
        console.log(finalObj);
        
        Final Output : {"key":[{"obj":"hello"},{"obj":"hello"}],"key2":{"obj":"world"},"key3":{"obj":"world"}}
        

        【讨论】:

          【解决方案5】:

          你可以使用reduce来实现这个

                  const obj = [{key: {val: 1}}, {key: {val: 2}}]
                  const reqObj = obj.reduce((acc, cur) => [...acc, cur.key],[])
                  console.log('reqObj: ', reqObj)

          【讨论】:

            猜你喜欢
            • 2017-09-22
            • 2018-06-21
            • 2019-10-19
            • 2013-12-31
            • 1970-01-01
            • 1970-01-01
            • 2019-07-30
            • 2023-01-19
            • 2018-05-13
            相关资源
            最近更新 更多