1

New to manipulating JSON, I appreciate the help! This project uses VueJs 2 if that makes a difference.

I am trying to update a key value, in this example it is "group" for a specific applicant identified by the ID.

I am trying to accomplish something along of lines of:

WHERE applicantID = 3 SET group = 4

This is a sample of the JSON I am dealing with:

{
    "applicantID" : 3,
    "fullName": "name",
    "value1": 30,
    "value1": 31,
    "value1": 40,
    "value1": 41,
    "value1": "50",
    "value1": "51",
    "group": 0,
    "flag": true,
},
{
    "applicantID" : 4,
    "fullName": "name",
    "value1": 30,
    "value1": 31,
    "value1": 40,
    "value1": 41,
    "value1": "50",
    "value1": "51",
    "group": 0,
    "flag": false,
}
3
  • 1
    Possible duplicate of How to access JSON encoded data of an array using javascript Commented Jan 12, 2018 at 22:34
  • This looks like it's part of an array. Assuming arr is a defined array, arr[0]["group"] = 4. Commented Jan 12, 2018 at 22:35
  • You have duplicate property names (value1) - that won't work. Commented Jan 12, 2018 at 22:44

3 Answers 3

8

You can do it like this:

var item = array.find(x => x.applicantID == 3);
if (item) {
  item.group = 4;
}

It will change a value of the group in the original array.

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

3 Comments

What if there is more than one item that has ID 3?
Fantastic! That was exactly what I needed. Thank you very much!
@Sergii what if you have to update multiple records then what would be the approach since this will update only one object in the array
1

if you have to compare multiple fields you can use this .as an adjustment onto Sergii's answer

var item = array.find(x => {
      return x.applicantID == 3 && x.fullName == "name" ;
     });
   if (item) {
     item.group = 4;
    }

Comments

0

You can update a specific value in a JSON array by first getting the specific index then accessing the object property name to edit the value as illustrated below


let users = [{name:"John", DOB:"1991", gender:"male"}, {name:"mary", DOB:"1993", gender:"female"}];

//change DOB of Mary
users[1].DOB = "1995";

NB You can also loop over the JSON array to update a value at a specific index using the same logic.

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.