Home > Enterprise >  Replace specific values for a key in nested object array JavaScript
Replace specific values for a key in nested object array JavaScript

Time:12-08

Hi I would like to know if there is a way to replace new incoming values for values that exist in a deeply nested object array.

original data

const data = [
    { id: "americano",
       data: [{x: "10",y: 0,}, {x: "11",y: 0,}, {x: "12",y: 0,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
    { id: "latte",
       data: [{x: "10",y: 0,}, {x: "11",y: 0,}, {x: "12",y: 0,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
    { id: "espresso",
       data: [{x: "10",y: 0,}, {x: "11",y: 0,}, {x: "12",y: 0,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
]

incoming data

const serverdata = [
    { "id": "latte",
        "data": [{"x": "12", "y": 30}]},
    {"id": "americano",
        "data": [{"x": "10","y": 20},{ "x": "13","y": 10}]},
    {"id": "espresso",
        "data": [{"x": "10","y": 30},{ "x": "11","y": 10},{ "x": "12","y": 20}]},
  ]

expected result

const newData = [
    { id: "americano",
      data: [{x: "10",y: 0,}, {x: "11",y: 0,}, {x: "12",y: 30,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
    { id: "latte",
       data: [{x: "10",y: 20,}, {x: "11",y: 0,}, {x: "12",y: 0,}, {x: "13",y: 10,}, {x: "14",y:0,}],},
    { id: "espresso",
       data: [{x: "10",y: 30,}, {x: "11",y: 10,}, {x: "12",y: 20,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
]

I want to replace the y values with incoming data but I'm not sure how :( help needed

CodePudding user response:

We can use Array.forEach() and Array.filter() to do it

const originData = [
    { id: "americano",
       data: [{x: "10",y: 0,}, {x: "11",y: 0,}, {x: "12",y: 0,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
    { id: "latte",
       data: [{x: "10",y: 0,}, {x: "11",y: 0,}, {x: "12",y: 0,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
    { id: "espresso",
       data: [{x: "10",y: 0,}, {x: "11",y: 0,}, {x: "12",y: 0,}, {x: "13",y: 0,}, {x: "14",y:0,}],},
]

const serverData = [
    { "id": "latte",
        "data": [{"x": "12", "y": 30}]},
    {"id": "americano",
        "data": [{"x": "10","y": 20},{ "x": "13","y": 10}]},
    {"id": "espresso",
        "data": [{"x": "10","y": 30},{ "x": "11","y": 10},{ "x": "12","y": 20}]},
  ]
  
originData.forEach(d1 => {
  let oData = d1.data
  let nData = serverData.find(e1 => e1.id === d1.id).data??[]
  oData.forEach(d2 => {
    let record = nData.find(e2 => e2.x === d2.x)
    if(record){
      d2.y = record.y
    }
  })
}) 

console.log(originData)

  • Related