gpt4 book ai didi

javascript - 如何在javascript中通过两个对象创建新对象

转载 作者:行者123 更新时间:2023-12-04 09:18:05 27 4
gpt4 key购买 nike

我想知道如何通过 javascript 中的两个对象创建新对象。
遍历 obj1,并添加 obj2 值,在 javascript 中创建新对象

function getObject(obj1, obj2){
let result={};
Object.keys(obj1).forEach(key=>{
if(key==="start" || key==="end"){
result.time= obj1.start+"-"+obj1.end,
result.qty= obj2.qty
}
})

}

var obj1 ={
start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

var obj2 = {
qty: 10,
amt: 120
}

预期产出
 {
time: "16:01-23:59"
val: 10 // represents obj2.qty,
totalqty: 1065,
totalamount: 8229170,
price: 120
}

最佳答案

您可以编写一个函数并获得所需的属性:

var obj1 ={
start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

var obj2 = {
qty: 10,
amt: 120
}

const merge = (obj1, obj2) => {
return {
time: obj1.start + '-' + obj1.end,
val: obj2.qty,
totalqty: obj1.totalqty,
totalamount: obj1.totalamount,
price: obj2.amt
};
}

console.log(merge(obj1, obj2));

此外,您可以使用 spread语法,但它合并了所有属性:

let obj1 ={
start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

let obj2 = {
qty: 10,
amt: 120
}

let merged = {...obj1, ...obj2};
console.log(merged );

或尝试使用 Object.assign()它也合并了所有属性:

var obj1 ={
start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170
}

var obj2 = {
qty: 10,
amt: 120
}

var result = Object.assign({}, obj1, obj2);
console.log(result);

Read more Object.assign() here.

关于javascript - 如何在javascript中通过两个对象创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63149517/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com