[英]Create an Dynamic Array Object with key value pairs
I need to create an Dynamic key value pairs from the existing object我需要从现有的 object 创建一个动态键值对
const balanceScheule = 1255;
const reqCost = [{Labour Cost: "1555"}, {Material Cost: "1575"}]; // key is dynamic and keeps on changing
const amfqtyCost = 1416;
Here the logic is to create an new array of object and subtract the amfqtyCost from reqCost这里的逻辑是创建一个新数组 object 并从reqCost中减去amfqtyCost
Logic i Have written我写的逻辑
reqCost.forEach(element => {
const adjustedAmount = Object.entries(element).map((m) => {
let adjustedAmount = parseInt(m[1]) - amfqtyCost;
return adjustedAmount;
});
// console.log(...adjustedAmount)
});
this return 139 and 159 which is (1555 - 1416 = 139) and (1575 1416 = 159) respectively这返回 139 和 159 分别是 (1555 - 1416 = 139) 和 (1575 1416 = 159)
Expected output:预期 output:
[{Labour Cost: "139"}, {Material Cost: "159"}]
How to do i merge?我该如何合并?
You just need to return the updated object from within map function.您只需从 map function 中返回更新的 object。 Also for the outer iteration use map instead of forEach to return the final result
同样对于外部迭代,使用 map 而不是 forEach 来返回最终结果
const balanceScheule = 1255; const reqCost = [{ 'Labour Cost': "1555", }, { 'Material Cost': "1575", }]; // key is dynamic and keeps on changing const amfqtyCost = 1416; const updatedData = reqCost.map(element => { return Object.assign({}, ...Object.entries(element).map(([key, value]) => { let adjustedAmount = parseInt(value) - amfqtyCost; return { [key]: String(adjustedAmount) }; })); }); console.log(updatedData);
You can do something like this:你可以这样做:
const reqCost = [{ 'Labour Cost': "1555" }, { 'Material Cost': "1575" }]; const amfqtyCost = 1416; const adjustedCost = reqCost.map(cost => ({ [Object.keys(cost)[0]]: (parseInt(Object.values(cost)[0]) - amfqtyCost).toFixed(0) })); console.log(adjustedCost); // OR, if you prefer to be a bit more verbose: const adjustedCost2 = reqCost.map(cost => { const [key, value] = Object.entries(cost)[0]; return { [key]: (parseInt(value) - amfqtyCost).toFixed(0) } }); console.log(adjustedCost2);
You can reverse the Object.entries
您可以反转
Object.entries
{ key : value } => [ [ key, value ] ]
transformation by using Object.fromEntries
使用
Object.fromEntries
进行转换
[ [ key, value ] ] => { key : value }
the code will look like this代码看起来像这样
reqCost.map((obj) =>
Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
key,
parseInt(value) - amfqtyCost,
])
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.