我正在使用_下划线。我想重命名特定键的值。
var users = [{
"_id": { "$oid":"3426" },
"name":"peeter"
}, {
"_id": { "$oid":"5a027" },
"name":"ken"
}, {
"_id": { "$oid":"5999" },
"name":"karmal"
}];
var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
在上面的 console.log(index)
输出中,我想编辑 key(name) 的值,即添加 karmal-Copy。
所需输出
{
"_id": {
"$oid": "5999"
},
"name": "karmal-Copy"
}
我只想添加 -Copy 和键(名称)值。
最佳答案
您可以只更新找到的对象。
var users = [{ _id: { $oid: "3426" }, name: "peeter" }, { _id: { $oid: "5a027" }, name:"ken" }, { _id: { $oid: "5999" }, name: "karmal" }],
item = _.find(users, function(o) { return o._id.$oid == '5999'; });
if (item) { // check if item exists
item.name += '-Copy'; // update property
}
console.log(users);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
关于javascript - 如何更新 JSON 对象中键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303911/