1

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

2
  • I guess this will help you stackoverflow.com/a/12482991/10321531 Commented Mar 17, 2021 at 5:23
  • With the given dataArr, seems to work Commented Mar 17, 2021 at 5:37

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can use map()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.