[英]Replace a field in a javascript Object? with splice and push, indexOf to splice is returning -1 value?
我有一個數組,隨時可能包含以下值的任意組合:
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') {
...
基本上,如果位置之一在positions數組中,則currentPositioning Object中的該位置應設置為true
..否則,它應保持為false
這個想法是..什么時候..
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
]
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.