skip to Main Content

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"
    }
]

4

Answers


  1.     const updatedArray = array.map(item => {
      if (item.studentname === "abc") {
        return {
          studentname: "abc",
          marks: parseInt(item.marks, 10) + 10
        };
      } else {
        return item;
      }
    });
    
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
  3. 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)
    
    Login or Signup to reply.
    • Loop through the array of objects
    • Check if the studentname property of the current object is equal to abc
    • If it is, add 10 to the marks property of the current object
    • After the loop, the array will be updated with the modified object
    const arr = [{"studentname": "abc", "marks": "20"},    
           {"studentname": "abc2","marks": "20" }];
    
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].studentname === "abc") {
            arr[i].marks = parseInt(arr[i].marks) + 10;
        }
    }
    
    console.log(arr);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search