admin管理员组

文章数量:1327849

Description: Have defined a JSON Object, as a global variable. var JSON_OBJECT = [];

[
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
]

JSON object (JSON_OBJECT) gets constructed by a function:jsonCreator

function jsonCreator() {

var af_Array = [];
var Trend_Array = [];
var selectedUsers = ['123','859','235']

for (var i = 0; i < 1; i++) {
    var af_keys = {}
    af_keys.formula_type = i;
    af_keys.lag = i;
    af_Array.push(af_keys);
}

for (var j = 0; j < 1; j++) {
    var trends_keys = {}
    trends_keys.is_active = j;
    Trend_Array.push(trends_keys);
}


for (var indexUsers = 0; indexUsers < selectedUsers.length; indexUsers++) {
    var jsonObj = {};
    jsonObj.user_id = selectedUsers[indexUsers]['rowId'];
    jsonObj.AF = af_Array;
    jsonObj.Trend = Trend_Array;
    JSON_OBJECT.push(jsonObj);
}
};

Problem Statement: Change the value of formula_type for user_id:123

Tried Below Code

var currentUserID = '123';
var formulaType = 'FORMULA-1'

Object.keys(JSON_OBJECT).forEach(function(k) {
if (currentUserID == JSON_OBJECT[k]['user_id']) {
    JSON_OBJECT[k]['AF'][0]['formula_type'] = formulaType;
}
});

Issue Facing: Above code changes the value of formula_type for user_id:123 and user_id:859

Resulting JSON:

[
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 'FORMULA-1',
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 'FORMULA-1',
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
]

Help would be appreciated.

var JSON_OBJECT = [
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
];

var currentUserID = '123';
var formulaType = 'FORMULA-1'

Object.keys(JSON_OBJECT).forEach(function(k) {
  if (currentUserID == JSON_OBJECT[k]['user_id']) {
      JSON_OBJECT[k]['AF'][0]['formula_type'] = formulaType;
  }
});
console.log(JSON_OBJECT);

Description: Have defined a JSON Object, as a global variable. var JSON_OBJECT = [];

[
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
]

JSON object (JSON_OBJECT) gets constructed by a function:jsonCreator

function jsonCreator() {

var af_Array = [];
var Trend_Array = [];
var selectedUsers = ['123','859','235']

for (var i = 0; i < 1; i++) {
    var af_keys = {}
    af_keys.formula_type = i;
    af_keys.lag = i;
    af_Array.push(af_keys);
}

for (var j = 0; j < 1; j++) {
    var trends_keys = {}
    trends_keys.is_active = j;
    Trend_Array.push(trends_keys);
}


for (var indexUsers = 0; indexUsers < selectedUsers.length; indexUsers++) {
    var jsonObj = {};
    jsonObj.user_id = selectedUsers[indexUsers]['rowId'];
    jsonObj.AF = af_Array;
    jsonObj.Trend = Trend_Array;
    JSON_OBJECT.push(jsonObj);
}
};

Problem Statement: Change the value of formula_type for user_id:123

Tried Below Code

var currentUserID = '123';
var formulaType = 'FORMULA-1'

Object.keys(JSON_OBJECT).forEach(function(k) {
if (currentUserID == JSON_OBJECT[k]['user_id']) {
    JSON_OBJECT[k]['AF'][0]['formula_type'] = formulaType;
}
});

Issue Facing: Above code changes the value of formula_type for user_id:123 and user_id:859

Resulting JSON:

[
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 'FORMULA-1',
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 'FORMULA-1',
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
]

Help would be appreciated.

var JSON_OBJECT = [
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
];

var currentUserID = '123';
var formulaType = 'FORMULA-1'

Object.keys(JSON_OBJECT).forEach(function(k) {
  if (currentUserID == JSON_OBJECT[k]['user_id']) {
      JSON_OBJECT[k]['AF'][0]['formula_type'] = formulaType;
  }
});
console.log(JSON_OBJECT);

Share edited Jun 26, 2018 at 6:20 WEshruth asked Jun 25, 2018 at 11:34 WEshruthWEshruth 7873 gold badges16 silver badges32 bronze badges 8
  • can you try data[0].AF[0].formula_type = "3";..where data will be JSON – Aravind S Commented Jun 25, 2018 at 11:39
  • 1 Your code works see the snippet. What's the problem now? – Ankit Agarwal Commented Jun 25, 2018 at 11:41
  • 2 This could be a problem with the way JSON_OBJECT is created. Those two AF values are likely referencing the same array, or the elements in the AF arrays are referencing the same object. That shouldn't happen with proper json objects of course but if you're creating those objects yourself then the bug might be there. – ccarton Commented Jun 25, 2018 at 11:47
  • 2 Yeah, the problem is in the creation. This line: jsonObj.AF = af_Array; doesn't copy, it just assigns a reference. All of the AF fields are referencing the same af_Array object. You need to do a deep copy. Same for the Trend_Array assignment. – ccarton Commented Jun 26, 2018 at 9:06
  • 1 If you're not sure about how to do a deep copy, the easiest way is to convert to and from a json string. i.e when af_Array is created save it as a string af_Array_str = JSON.stringify(af_Array) and then when you create your objects use jsonObj.AF = JSON.parse(af_Array_str) – ccarton Commented Jun 26, 2018 at 13:30
 |  Show 3 more ments

5 Answers 5

Reset to default 3

<script src="https://ajax.googleapis./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    
        var currentUserID = '123';
		var formulaType = 'FORMULA-1';
        
        var JSON_OBJECT = '[{    "user_id": "123",    "AF": [        {            "formula_type": 0,            "lag": 0        }    ],    "Trend": [        {            "is_active": 0        }    ]},{    "user_id": "859",    "AF": [        {            "formula_type": 0,            "lag": 0        }    ],    "Trend": [        {            "is_active": 0        }    ]}]';

        var obj = jQuery.parseJSON(JSON_OBJECT);
       // var obj1 = jQuery.parseJSON(JSON_OBJECT);
$.each(obj, function(k,value) {
  if(value.user_id == currentUserID){
    JSON_OBJECT.AF = formulaType;
    obj[k]['AF'][0]['formula_type'] = formulaType;
  }
})	
		var myJSON = JSON.stringify(obj);	
        console.log(myJSON)
  
});
</script>

The problem was with the creation of JSON, jsonCreator(). Line jsonObj.AF = af_Array; was not copying, it was just assigning a reference.

Solution found, with the suggestion of @ccarton, converted JSON_OBJECT to string and parse back.

var currentUserID = '123';
var formulaType = 'FORMULA-1'

var JSON_OBJECT1 = JSON.stringify(JSON_OBJECT); 
JSON_OBJECT = JSON.parse(JSON_OBJECT1)

Object.keys(JSON_OBJECT).forEach(function(k) {
if (currentUserID == JSON_OBJECT[k]['user_id']) {
    JSON_OBJECT[k]['AF'][0]['formula_type'] = formulaType;
}
});

Using Array map() method :

var jsonObj = [
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
];

var currentUserID = '123';
var formulaType = 'FORMULA-1';

jsonObj.map(obj => {
  if (obj.user_id == currentUserID) {
    for (var i in obj["AF"]) {
      obj["AF"][i].formula_type = formulaType;
    }
  }
});

console.log(jsonObj);

Using JavaScript for ... in loop :

var jsonObj = [
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
];

var currentUserID = '123';
var formulaType = 'FORMULA-1';

for (var i in jsonObj) {
  if (jsonObj[i]["user_id"] == currentUserID) {
    for (var j in jsonObj[i]["AF"]) {
      jsonObj[i]["AF"][j].formula_type = formulaType;
    }
  }
}

console.log(jsonObj);

Try following:

if (JSON_OBJECT.length > 0) {
    JSON_OBJECT.forEach(function(obj, index) {
    if (obj.user_id == 123) {
        if (obj.hasOwnProperty('AF')) {
        obj.AF.forEach(function(obj, index) {
            if (obj.hasOwnProperty('formula_type')) {
            obj.formula_type = 'FORMULA-1';
          }
        });
        }
    }

  });
}

Explanation: Here JSON_OBJECT is an array of objects. So we need to loop into the array first.

JSFiddle

The code snippet below works:

var JSON_OBJECT = [
{
    "user_id": "123",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
},
{
    "user_id": "859",
    "AF": [
        {
            "formula_type": 0,
            "lag": 0
        }
    ],
    "Trend": [
        {
            "is_active": 0
        }
    ]
}
];

var currentUserID = '123';
var formulaType = 'FORMULA-1'

Object.keys(JSON_OBJECT).forEach(function(k) {
  if (currentUserID == JSON_OBJECT[k]['user_id']) {
      JSON_OBJECT[k]['AF'][0]['formula_type'] = formulaType;
  }
});
console.log(JSON_OBJECT);

Good luck !

本文标签: javascriptChanging the value of JSON object39s keychanges other values alsoStack Overflow