如何在JSON中重构和硬编码forEach ?



我试图重组一个给定的JSOn体,并添加一些硬编码参数到它使用forEach。我似乎被卡住了,因为我没有成功注入硬编码值的方式,我想要的。以下是我到目前为止所能做的:

let jsonBody = {
items: [
{ name: "item1", price: 12.99 },
{ name: "item2", price: 9.99 },
{ name: "item3", price: 19.99 }
]
};
let newJsonBody = [];
jsonBody.items.forEach(function (item) {
newJsonBody[item.name] = {
name: item.name,
price: item.price,
appUrl: "https://apps.google.com/",
stage: "accepted"
};
});
console.log(newJsonBody);

这是我想要的结果:

{
inputs: [
data: {
name: 'item1',
price: 12.99,
appUrl: 'https://apps.google.com/',
stage: 'accepted'
},
data: {
name: 'item2',
price: 9.99,
appUrl: 'https://apps.google.com/',
stage: 'accepted'
},
data: {
name: 'item3',
price: 19.99,
appUrl: 'https://apps.google.com/',
stage: 'accepted'
}
]
}

const data = {
items: [
{ name: "item1", price: 12.99 },
{ name: "item2", price: 9.99 },
{ name: "item3", price: 19.99 }
]
}
const result = {
inputs: data.items.map(i=>({
data: {
...i,
appUrl: 'https://apps.google.com/',
stage: 'accepted'
}
}))
}
console.log(result)

最新更新