I have an array that at any point may contain any combination of the following values:
var positions = ['first', 'second', 'third', 'fourth'];
The goal is to rebuild a Javascript Object that, by default, is set to:
currentPositioning = { 'positioning': [
{ 'first': false },
{ 'second': false },
{ 'third': false },
{ 'fourth': false }
]
};
The positions array is looped through to rebuild the currentPositioning Object:
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') {
...
Basically, if one of the positions is in the positions array, then that position in the currentPositioning Object should be set to true
..otherwise it should remain false
The idea is that..when..
var positions = ['first', 'second', 'third'];
..then..
currentPositioning = { 'positioning': [
{ 'first': true },
{ 'second': true },
{ 'third': true },
{ 'fourth': false }
]
};
For some reason though, right now the index = -1
.. every time .. so the result keeps turning to something like this!? :
currentPositioning = { 'positioning': [
{ 'first': false },
{ 'second': false },
{ 'third': false },
{ 'fourth': false },
{ 'first': true },
{ 'second': true },
{ 'third': true },
]
};
You can use Underscore.js to do this (I've added some temp variables to improve readibility):
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
]
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.