如何使用JavaScript合并两个对象?

时间:2019-01-14 13:47:05

标签: javascript lodash

a = {
    coffee: 'Coffees',
    mango: '10 Mangos',
    shoe: '2 Shoes',
    bag: '5 Bags',
    abc: 'D E F'
}

b = {
    coffee,
    abc,
    bag,
}


mergerd_output_will_be = {
    coffee: 'Coffees',
    abc: 'D E F',
    bag: '5 Bags'
}

如何合并这样的'a'对象? “ b”对象键仅包含在输出对象中。

5 个答案:

答案 0 :(得分:2)

您可以使用Array.reduce并使用每个键值构造一个对象。

    let a = {
        coffee: 'Coffees',
        mango: '10 Mangos',
        shoe: '2 Shoes',
        bag: '5 Bags',
        abc: 'D E F'
    }
    let b = {'coffee':null, 'abc':null, 'bag':null};
    let c = Object.keys(b).reduce((current,key)=>({...current, [key]:a[key]}), {});
    console.log(c);

答案 1 :(得分:1)

_.pick()来自对象a,对象b的{​​{3}}:

const a = {
  coffee: 'Coffees',
  mango: '10 Mangos',
  shoe: '2 Shoes',
  bag: '5 Bags',
  abc: 'D E F'
}

const b = {
  coffee: null,
  abc: null,
  bag: null
}

const result = _.pick(a, _.keys(b))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 2 :(得分:0)

您提供的初始代码无效(变量b)

您可以进行以下操作:


const a = {
    coffee: 'Coffees',
    mango: '10 Mangos',
    shoe: '2 Shoes',
    bag: '5 Bags',
    abc: 'D E F'
}

const props = ['coffee', 'abc', 'bag'];

const mergerd_output_will_be = {};
props.forEach(propName => mergerd_output_will_be[propName] = a[propName]);

const a = {
    coffee: 'Coffees',
    mango: '10 Mangos',
    shoe: '2 Shoes',
    bag: '5 Bags',
    abc: 'D E F'
}

const b = {coffee: null, abc: null, bag: null};

const mergerd_output_will_be = {...b};
Object.keys(mergerd_output_will_be).forEach(propName => 
  mergerd_output_will_be[propName]=a[propName]
)

答案 3 :(得分:0)

基本上,您有两种方法,使用... spread operatorObject.assign()

const coffee = 'Coffees'
const abc = 'abc';
const bag = 'bag'

const a = {
  coffee: 'Coffees',
  mango: '10 Mangos',
  shoe: '2 Shoes',
  bag: '5 Bags',
  abc: 'D E F'
}

const b = {
  coffee,
  abc,
  bag,
}

const result1 = {...a, ...b};
const result2 = Object.assign({}, a, b)

console.log(result1)
console.log(result2)

答案 4 :(得分:0)

首先,对象应该是键值对,为此,您可以将b更改为数组,例如b = ['coffee','D E F','5 Bags']

然后,使用下面的代码生成预期的输出。

let a = {
  coffee: 'Coffees',
  mango: '10 Mangos',
  shoe: '2 Shoes',
  bag: '5 Bags',
  abc: 'D E F'
 };
 let b = ['coffee', 'abc', 'bag'];
let output = {};
for( let i = 0; i < b.length; i++) {
 output[b[i]] = a[b[i]];
}