Home > Back-end >  How to restructure and hardcode a forEach in a JSON body?
How to restructure and hardcode a forEach in a JSON body?

Time:01-08

I am trying to restructure a given JSOn body and add some hardcoded parameters into it using a forEach. I seem to be stuck as I am not getting successful injecting the hardcoded values the way I want. This is what I have been able to do so far:

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);

And this is my desired result:

{
    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'
    }
  ]
}

CodePudding user response:

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)

  • Related