我有一个数组,它在任何时候都可能包含以下值的任意组合:
var positions = ['first', 'second', 'third', 'fourth'];
目标是重建一个 Javascript 对象,默认设置为:
currentPositioning = { 'positioning': [
{ 'first': false },
{ 'second': false },
{ 'third': false },
{ 'fourth': false }
]
};
循环遍历位置数组以重建 currentPositioning 对象:
positions.forEach(setPositions);
function setPositions(element, index, array) {
if (element == 'first') {
// define objSplice object
var objSplice = {};
// set object of 'array.element' to false .. {'element': false}
objSplice[element] = false;
console.log('objSplice = ' + JSON.stringify(objSplice));
// find index that matches {'element': false}
var index = currentPositioning["positioning"].indexOf( objSplice );
console.log('index = ' + index);
if (index > -1) {
// remove index that matches {'element': false}
currentPositioning["positioning"].splice(index, 1);
}
// define obj object
var obj = {};
// set obj object of 'array.element' to true .. {'element': true}
obj[element] = true;
// add {'element': true} to array
currentPositioning["positioning"].push( obj );
}
if (element == 'second') {
...
基本上,如果位置数组中存在一个位置,则 currentPositioning 对象中的该位置应设置为 true
..否则应保留 假
这个想法是......当......
var positions = ['first', 'second', 'third'];
..然后..
currentPositioning = { 'positioning': [
{ 'first': true },
{ 'second': true },
{ 'third': true },
{ 'fourth': false }
]
};
由于某种原因,现在 index = -1
.. 每次 .. 所以结果不断变成这样!? :
currentPositioning = { 'positioning': [
{ 'first': false },
{ 'second': false },
{ 'third': false },
{ 'fourth': false },
{ 'first': true },
{ 'second': true },
{ 'third': true },
]
};
最佳答案
您可以使用Underscore.js为此(我添加了一些临时变量以提高可读性):
var positions = ['first', 'second', 'third'];
var updatedPositions = _.map(['first', 'second', 'third', 'fourth'], function(p) {
var json={};
json[p] = _.contains(positions,p);
return json;
});
var currentPositioning = { 'positioning': [
updatedPositions
]
};
关于javascript - 替换 javascript 对象中的字段?使用 splice 和 push,splice 的 indexOf 返回 -1 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24658666/