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

ehxuflar  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(126)

我尝试重新构造一个给定的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'
    }
  ]
}
uqdfh47h

uqdfh47h1#

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)

相关问题