0

I'm having a JSON data like this

const dataArr = [{
        id: "8",
        data: { label: "node 4" },
        position: { x: 0, y: 0 },
        selectable: true,
      },
      {
        id: "e12",
        source: "1",
        target: "2b",
        type: "smoothstep",
        animated: false,
        style: { stroke: "", width: "" },
      },
      ....
      ]

How can I update value of stroke - style: { stroke: "", width: "" }, ?

I tried

let tempArr = [...dataArr];
tempArr.filter((x) => x.target == "someValue").forEach((x)=> {x.style.stroke = "#SomeData"})

But got error : Uncaught TypeError: "stroke" is read-only

Nithish
  • 5,393
  • 2
  • 9
  • 24
Alex
  • 727
  • 1
  • 13
  • 32

2 Answers2

1

You can use map()

const tempArr = dataArr.map((data) => {
  if(data.target === "someValue"){
    return {
      ...data,
      style: {
        ...data.style,
        stroke: "#HASH_CODE",
      }
    }
  }
  return data;
});

kyun
  • 9,710
  • 9
  • 31
  • 66
1

You can use Array.map and updated the value only for those objects which are satisfying the condition else just return the same object.

const dataArr = [{id:"8",data:{label:"node 4"},position:{x:0,y:0},selectable:true},{id:"e12",source:"1",target:"2b",type:"smoothstep",animated:false,style:{stroke:"",width:""}}]

const updateStroke = (data, filterBy, updatedValue) => {
  return data.map(obj => {
    //Update only if the condition is matching
    if(obj.target === filterBy) {
      return {
        ...obj,
        style: {
          ...obj.style,
          stroke: updatedValue
        }
      }
    }
    //else return the object
    return { ...obj };
  })
}

console.log(updateStroke(dataArr, "2b", "black"));
.as-console-wrapper {
  max-height: 100% !important;
}
Nithish
  • 5,393
  • 2
  • 9
  • 24