【问题标题】:Map two objects in javascript在javascript中映射两个对象
【发布时间】:2021-01-11 02:18:05
【问题描述】:

我有两个对象:

let obj1 = { key1: 'someValue', key2: 'someValue2'}

let obj2 = { someValue: 'otherValue', someValue2: 'otherValue2'}

obj1 的值实际上是 obj2 中的一个键。

我想要一个新对象let obj3 = { key1: 'otherValue', key2: 'otherValue2'}

我尝试使用 Object.keysObject.values 但没有成功。你们能帮帮我吗?

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:

    您可以使用Object.keys()array#reduce。遍历第一个对象中的每个键,然后对于每个键,在第二个对象中查找以获取值并将其放入结果对象中。

    const obj1 = { key1: 'someValue', key2: 'someValue2'},
          obj2 = { someValue: 'otherValue', someValue2: 'otherValue2'},
          result = Object.keys(obj1).reduce((r,k) => {
            r[k] = obj2[obj1[k]];
            return r;
          },{});
    console.log(result);

    【讨论】:

      【解决方案2】:

      您可以使用Object.entries

      let obj1 = { key1: 'someValue', key2: 'someValue2'};
      let obj2 = { someValue: 'otherValue', someValue2: 'otherValue2'};
      
      const result = {};
      Object.entries(obj1).map(item => {
        result[item[0]] = obj2[item[1]];
      });
      console.log(result);

      【讨论】:

        【解决方案3】:

        这可以通过目标的值将目标的键映射到配置值来实现。

        const obj1 = { key1: 'someValue', key2: 'someValue2' }
        const obj2 = { someValue: 'otherValue', someValue2: 'otherValue2' }
        
        const replaceProperties = (target, config) =>
          Object.entries(target).reduce((result, entry) =>
            (([ key, value ]) =>
              ({ ...result, [key]: config[value]  }))
            (entry), {});
        
        console.log(replaceProperties(obj1, obj2));
        .as-console-wrapper { top: 0; max-height: 100% !important; }

        代码高尔夫

        如上所见,整个函数可以用一行来表示。 :)

        f=(t,c)=>Object.entries(t).reduce((r,e)=>(([k,v])=>({...r,[k]:c[v]}))(e),{})
        a={key1:'someValue',key2:'someValue2'}
        b={someValue:'otherValue',someValue2:'otherValue2'}
        console.log(f(a, b))
        .as-console-wrapper { top: 0; max-height: 100% !important; }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-14
          相关资源
          最近更新 更多