Javascript/Jquery 中的对象数组的子集化和编辑
Subsetting and editing array of objects in Javascript/Jquery
我在 Javascript 中有一个对象数组,我想根据键值匹配对其进行子集化。原则上我想访问我的数组 js_obj
,更改一些 cond
为真的对象然后继续。
假设数组看起来像这样
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"
和这个 selected 对象,我想将 .type
更改为 "type_abc"
。
我能够使用 each
和 select 条件适用的对象并根据需要更改其 .type
,但我想在原始数组中执行此操作。我不只是想过滤掉这个对象,而是找到它,编辑它,然后让数组保持修改后的状态。
我找到了参考 underscore.js 的相关帖子,但我想我不知道要寻找哪种方法。
谁能帮我解决这个 indexing/subsetting 问题?
循环数组,检查条件并修改将其保留在原始数组中:
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 中有一个对象数组,我想根据键值匹配对其进行子集化。原则上我想访问我的数组 js_obj
,更改一些 cond
为真的对象然后继续。
假设数组看起来像这样
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"
和这个 selected 对象,我想将 .type
更改为 "type_abc"
。
我能够使用 each
和 select 条件适用的对象并根据需要更改其 .type
,但我想在原始数组中执行此操作。我不只是想过滤掉这个对象,而是找到它,编辑它,然后让数组保持修改后的状态。
我找到了参考 underscore.js 的相关帖子,但我想我不知道要寻找哪种方法。
谁能帮我解决这个 indexing/subsetting 问题?
循环数组,检查条件并修改将其保留在原始数组中:
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");