我有一些对象数据想要乘以一个数字,问题是我想要与某些名称匹配的所有属性或子属性乘以该数字,而不知道数据的实际类型
这是一个例子:
// original api response data
let data = {
id: 4,
price: 100,
discount: 10,
total_price: 90,
create_date: '2024-09-06T14:35:42.759Z',
parent_id: 3,
parent: {
id: 3,
price: 1000,
discount: 0,
total_price: 1000,
create_date: '2024-09-06T13:35:42.759Z',
},
items: [
{
id: 10,
name: 'item 1',
cost: 3,
price: 5,
quantity: 5
},
],
others: {
otherValues: [
{
id: 9,
name: 'other 1',
price: 10,
quantity: 1
},
]
}
}
// calculate function
const calculate = (data, multipler, keys) => {
// the lodash magic
...
}
// calculating the data
let calculated = calculate(data, 1.5, ['price', 'total_price', 'cost'])
/*
expected result:
let data = {
id: 4,
price: 150,
discount: 10,
total_price: 135,
create_date: '2024-09-06T14:35:42.759Z',
parent_id: 3,
parent: {
id: 3,
price: 1500,
discount: 0,
total_price: 1500,
create_date: '2024-09-06T13:35:42.759Z',
},
items: [
{
id: 10,
name: 'item 1',
cost: 4.5,
price: 7.5,
quantity: 5
},
],
others: {
otherValues: [
{
id: 9,
name: 'other 1',
price: 15,
quantity: 1
},
]
}
}
*/
在示例中,仅将名为“price”、“total_price”和“cost”的属性和子属性相乘,并且我提供的对象是被发送回的形状不同并试图对每个人进行操作并不是一个好主意
我主要尝试使用 lodash 地图,但我无法让它工作
一个经典的迭代器。这是一个递归,递归到作为对象的值,做它的事情。它会替换原值,但如果您想保留原始树,也可以复制原始值。
// calculate function
const calculate = (obj, multiplier, keys) => {
if (!obj) {
return obj
}
Object.keys(obj).forEach(key => {
if (keys.indexOf(key) >= 0) {
obj[key] *= multiplier
}
if (typeof obj[key] === "object") {
obj[key] = calculate(obj[key], multiplier, keys)
}
})
return obj;
}
// original api response data
let data = {
id: 4,
price: 100,
discount: 10,
total_price: 90,
create_date: '2024-09-06T14:35:42.759Z',
parent_id: 3,
parent: {
id: 3,
price: 1000,
discount: 0,
total_price: 1000,
create_date: '2024-09-06T13:35:42.759Z',
},
items: [{
id: 10,
name: 'item 1',
cost: 3,
price: 5,
quantity: 5
}, ],
others: {
otherValues: [{
id: 9,
name: 'other 1',
price: 10,
quantity: 1
}, ]
}
}
// calculating the data
let calculated = calculate(data, 1.5, ['price', 'total_price', 'cost'])
console.log(calculated)
.as-console-wrapper {
min-height: 100%;
}