Skip to content
Advertisement

Modify values inside a Javascript object

I have the following array if objects:

[{id: 0
name: "Weight"
options: [
"250gr","500gr"],
position: 0
variation: true
visible: true},
{id: 0
name: "Roast"
options: ["Light", "Medium, "Dark],
position: 0
variation: true
visible: true},
{id: 0
name: "Packaging"
options: [
"Tin","Card"],
position: 0
variation: true
visible: true}
]

Then i elaborate the following one:

[{id: 0, name: "Weight", option: "250gr"},
{id: 0, name: "Roast", option: "Medium"},
{id: 0, name: "Packaging", option: "Card"},
{id: 0, name: "Weight", option: "250gr"},
{id: 0, name: "Roast", option: "Light"},
{id: 0, name: "Packaging", option: "Card"}
]

is it possible to change the value of ‘options’ array of the first one, according to the second set of options? i need to obtain something like:

[{id: 0
    name: "Weight"
    options: [
    "250gr"],
    position: 0
    variation: true
    visible: true},
    {id: 0
    name: "Roast"
    options: ["Light", "Medium"],
    position: 0
    variation: true
    visible: true},
    {id: 0
    name: "Packaging"
    options: [
    "Card"],
    position: 0
    variation: true
    visible: true}
    ]

Advertisement

Answer

i solved this way (locattributes is the first object, newopt the second) i don’t know if there is a more efficient way to do i

for (const property in locattributes) {
      let locop = [];
      locattributes[property].options = [];
      newopt.forEach((no) => {
        if (no.name === locattributes[property].name) {
          if (locop.indexOf(no.option) === -1) {
            locop.push(no.option);
          }
        }
      });
      locattributes[property].options = locop;
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement