将两个对象合并在一起

时间:2018-04-18 23:00:20

标签: javascript react-native

我有两个对象:

a = {id: "1", value: "hello"}
b = {id: "2", value: "bye"}

我要转换为:

c = { 1: "hello", 2: "bye" }

因此创建一个没有任何嵌套主题的新对象。

我尝试了几种方法但却没有得到我需要的东西。 如:

Object.keys(a).forEach((key) => { a[key] = b[key]; });

5 个答案:

答案 0 :(得分:6)

您可以使用.reduce

a = {id: "1", value: "hello"}
b = {id: "2", value: "bye"}
c = [a, b].reduce((carry, current) => { carry[current.id] = current.value; return carry }, {})
console.log(c)

答案 1 :(得分:1)

只需创建一个新的空白对象并复制值..



var a = {id: "1", value: "hello"}
var b = {id: "2", value: "bye"}

var c = {};
c[a.id] = a.value;
c[b.id] = b.value;

console.log(c);




如果使用新的ESNext功能,则更容易。



const a = {id: "1", value: "hello"}
const b = {id: "2", value: "bye"}

const c = {
  [a.id]: a.value,
  [b.id]: b.value
};

console.log(c);




答案 2 :(得分:1)

您可以使用Object.assignmap()方法执行此操作。



const a = {id: "1", value: "hello"}
const b = {id: "2", value: "bye"}

const result = Object.assign({}, ...[a, b].map(({id, value}) => ({[id]: value})));
console.log(result)




答案 3 :(得分:1)

简单的方法,循环所以它可以完成所有元素:

var list = [
    {id: "1", value: "hello"},
    {id: "2", value: "bye"}
    // ... more elements
];

var c = {};
list.forEach(function (element) {
    c[element['id']] = element['value'];
    // or c[element.id] = element.value;
});

答案 4 :(得分:1)

另一种选择



# page counts out
spring.cloud.stream.bindings.pcout.destination=pcs
spring.cloud.stream.bindings.pcout.producer.use-native-encoding=true
spring.cloud.stream.kafka.streams.bindings.pcout.producer.key-serde=org.apache.kafka.common.serialization.Serdes$StringSerde
spring.cloud.stream.kafka.streams.bindings.pcout.producer.value-serde=org.apache.kafka.common.serialization.Serdes$LongSerde
#
# page counts in
spring.cloud.stream.bindings.pcin.destination=pcs
spring.cloud.stream.bindings.pcin.consumer.use-native-decoding=true
spring.cloud.stream.bindings.pcin.group=pcs
spring.cloud.stream.bindings.pcin.content-type=application/json
spring.cloud.stream.bindings.pcin.consumer.header-mode=raw
spring.cloud.stream.kafka.streams.bindings.pcin.consumer.key-serde=org.apache.kafka.common.serialization.Serdes$StringSerde
spring.cloud.stream.kafka.streams.bindings.pcin.consumer.value-serde=org.apache.kafka.common.serialization.Serdes$LongSerde




相关问题