xhutpl xhutpl - 2 days ago 4
JSON Question

add key and value in json file using javascript

the data.json look like

[
{
"uid": 11111,
"status": "ADMIN"
},
{
"uid": 22222
}
]


i use lodash for find the key uid = 22222


_.find(data, (item)=>item.uid === 22222)


the result is {uid: 22222}

how can i add some status: "value" in result that i find by lodash
i expect like this

[
{
"uid": 11111,
"status": "ADMIN"
},
{
"uid": 22222,
"status": "USER"
}
]

Answer

This gives you the object, so you can just work with it directly:

_.find(data, item => item.uid === 22222).status = "USER";

Otherwise you can get the index and update the entire object.

const idx = _.findIndex(data, item => item.uid === 22222);
data[idx] = Object.assign(data[idx], {status: "USER"});

Depending on the environment you're working in, you don't need to use lodash and you can just use data.find.