gpt4 book ai didi

javascript - 更改 JSON 对象的键值,也会更改其他值

转载 作者:行者123 更新时间:2023-12-01 02:27:13 25 4
gpt4 key购买 nike

描述:定义了一个 JSON 对象,作为全局变量。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 对象 (JSON_OBJECT) 由函数构造: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);
}
};

问题陈述:更改 user_id:123formula_type

尝试了以下代码

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

面临的问题:上面的代码更改了 user_id:123user_id:859

formula_type

生成的 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
}
]
}
]

如果有帮助,我们将不胜感激。

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

最佳答案

<script src="https://ajax.googleapis.com/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>

关于javascript - 更改 JSON 对象的键值,也会更改其他值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com