Home > Software design >  How to update old value with new value in array [React native]
How to update old value with new value in array [React native]

Time:12-14

I have array

[{
        "studentname": "abc",
        "marks": "20"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]

I have want add 10 more marks where studentname=abc into marks so how do this

eg.10 20=30 so the output will be

[{
        "studentname": "abc",
        "marks": "30"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]

CodePudding user response:

    const updatedArray = array.map(item => {
  if (item.studentname === "abc") {
    return {
      studentname: "abc",
      marks: parseInt(item.marks, 10)   10
    };
  } else {
    return item;
  }
});

CodePudding user response:

This is one clean way to do it.

const x= [{
        "studentname": "abc",
        "marks": "20"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]

x.forEach(function(obj) {
    if (obj.studentname === 'abc') {
        obj.marks = Number(obj.marks)   10
    }
});

console.log(x)

CodePudding user response:

const array= [{
        "studentname": "abc",
        "marks": "20"
    },
    {
        "studentname": "abc2",
        "marks": "20"
    }
]

array.map((item,index)=> {
    if (item.studentname == 'abc') {
        item.marks = Number(item.marks)   10
    }
});

console.log("Your Updated Array Here:->",array)
  • Related