我有一个 Javascript 对象数组,我想根据键值匹配对其进行子集化。原则上我想访问我的数组js_obj
,更改一些cond
为true的对象,然后继续。
假设数组如下所示
js_obj = [{
word: "airport",
pic: "<img id='pic' src='../images/location/airport.png'/>",
cat: "location",
type: "undetermined"
}, {
word: "station",
pic: "<img id='pic' src='../images/location/station.png'/>",
cat: "location",
type: "undetermined"
}]
我现在想要访问js_obj
,其中.word ==“station”
并且我想将这个选定对象的.type
更改为“type_abc”
。
我能够使用each
并选择条件适用的对象并根据需要更改其.type
,但我想在原始数组中执行此操作。我不想简单地过滤掉这个对象,而是找到它,编辑它,并将数组保留在修改状态。
我找到了引用 underscore.js 的相关帖子,但我想我不知道该寻找哪种方法。
有人可以帮我解决这个索引/子集问题吗?
最佳答案
循环数组,检查条件并修改会将其保留在原始数组中:
function modifyArrOfObjs(arr, key, condition, updateKey, updateValue) {
arr.forEach(function(obj) {
if (obj[key] == condition) {
obj[updateKey] = updateValue;
}
});
}
modifyArrOfObjs(js_obj, "word", "station", "type", "type_abc");
关于javascript - 在 Javascript/Jquery 中对对象数组进行子集化和编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951810/