如何连接两个对象并替换值?

问题描述 投票:0回答:3

我正在尝试连接两个对象。我需要合并两个对象并基于箭头内的“beforeVist”对象值。

我的两个物体在下面:

const beforeVist = {
  name : '<<name>>',
  age : '<<age>>',
  place : '<<place>>'
};

const afterVist = {
  name : 'Robin',
  age : 22,
  place : 'Mars'
}

var Updated = {...afterVist, ...beforeVist};
console.log(Updated)

当我尝试执行下面的 console.log() 函数输出时,

{
    name : 'Robin',
    age : 22,
    place : 'Mars'
}

这就是我的预期输出。我不确定这是正确的方法。

提前致谢!

javascript javascript-objects
3个回答
0
投票

你也可以使用Object.assign

const a = {p1: 12, p2: 23}
const b = {p2: 34, p3: 'adfa'}
let c = Object.assign(b, a)
// c contains:
{p2: 23, p3: "adfa", p1: 12}

如果您关心不变性,您可以提供单独的“结果”对象:

const res = Object.assign({}, b, a)

// a 和 b 仍保持原始值

注意:属性 ORDER 将从左到右驱动(“p2”是 B 中的第一个 prop,但 A 中的第二个),但 VALUES 从右到左(result.p2 包含来自最右边对象的值具有这样的属性 - 即 A.p2 覆盖 B.p2


0
投票

这是正确的方法。你应该使用 object sprad

let merged = {...obj1, ...obj2};

ES5 及更早版本的方法

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

因为<< >>总是位于前两个位置和后两个位置,我们可以简单地切片,然后重新分配值。

const beforeVist = {
    name: '<<name>>',
    age: '<<age>>',
    place: '<<place>>'
};

const afterVist = {
    name: '<<Robin>>',
    age: '<<22>>',
    place: '<<Mars>>'
}

var Updated = {...beforeVist, ...afterVist };

Object.entries(Updated).forEach(([key, value]) => {

    let val = value.slice(2, value.length - 2);
    Updated[key] = val;
})


console.log(Updated)


0
投票

目前,您只是用

afterVist
中的属性覆盖
beforeVist
中的属性,并且由于属性名称相同,因此您本质上只是进行浅复制。如果您的
afterVist
具有与
beforeVist
不同的属性名称(以及为什么我在下面的
beforeVist
中提供了不同的属性名称 - 以表明它们不必相同并且值是根据
<<key>>
)

中指定的key抓取

相反,您可以通过映射

原始对象的
Object.fromEntries()来使用
Object.entries()
,并在键上使用replace来提取键名称,如下所示:

const beforeVist = { myName: '<<name>>', myAge: '<<age>>', myPlace: '<<place>>' }; 
const afterVist = { name: 'Robin', age: 22, place: 'Mars' };

const result = Object.fromEntries(Object.entries(beforeVist).map(([key, value]) => [
  key,
  value.replace(/<<([^>>]*)>>/, (_, g) => afterVist[g])
]));
console.log(result);

© www.soinside.com 2019 - 2024. All rights reserved.