简体   繁体   中英

javascript: How do I add a JSON object with a push()?

So I hacked this code from somewhere else, but have an object variable to store x,y values in an array every time a hex is clicked, defined with two functions, one to add an element and one to remove the last element

var objMoves = {
    length: 0,

    addElem: function addElem(elem) {
        // obj.length is automatically incremented 
        // every time an element is added.
        [].push.call(this, elem);
    },
    removeElem: function removeElem(last) {
        // this removes the last item in the array
        [].splice.call(this,last, 1);
    }

};

I call it like this:

objMoves.addElem({ x: hexX, y: hexY });

Result if I dump the objMoves into the console log is "{"0":{"x":2,"y":1},"length":1}"

However, what I really want is something like

objMoves.addElem({ x: hexX, y: hexY },stackID:"abcdef");

So the result would be something like

{stackId:"abcdef",moves:[{"x":2,"y":1},{"x":3,"y":4}]} 

{stackId:"xyz",moves:[{"x":5,"y":2},{"x":6,"y":2},{"x":7,"y":2}]} 

etc, where the inner array gets added to for a given stackID . I think I need to nest the objects?

push() is for arrays, not objects, so use the right data structure.

 var objMoves = [];
// ...
data[0] = { "": "", "": "" };
data[1] = { ....};
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
if ( data[index].objMoves ) {
    tempData.push( data );
}
}
 data = tempData;

or deal with it like it is an object. while Objects does not support push property, you can save it as well using the index as key.

It sounds like what you're looking for is something like this:

 var objMoves = { addElem: function(id, elem) { var obj = this[id] || { stackId: id, moves: [] }; obj.moves.push(elem); this[id] = obj; }, removeElem: function(id, last) { this[id].moves.splice(last, 1); } } objMoves.addElem("abcdef", {x: 123, y: 456}); objMoves.addElem("xyz", {x: 1, y: 2}); objMoves.addElem("abcdef", {x: 100, y: 50}); console.log(objMoves); 

The functions take a stack ID as a parameter, so they can use that as a key into the object to find the sub-object with that ID. The moves are stored in an array in that sub-object.

I was a little bit fascinated from the code, that you have taken from the MDN JavaScript reference site . It shows us how we could use an object as an array. And so I wrote some functions to do it.

Solution with all, what you need:

 var objMoves = { // objMoves.length is automatically incremented every time an element is added length: 0, //add an object to new(with stackId) or given(by stackId) array element addElem: function(object, stackId) { var index = this.getElemIndex(stackId); if(index > -1) this[index].moves.push(object); else [].push.call(this, {stackId: stackId, moves: [object]}) }, //remove the array element on lastElemIndex removeElem: function(lastElemIndex) { [].splice.call(this, lastElemIndex, 1) }, //remove the object on lastElemIndex from the array element with stackId removeMovesElem: function(stackId, lastElemIndex) { var index = this.getElemIndex(stackId); if(index > -1) this[index].moves.splice(lastElemIndex, 1) }, //get the array element index by stackId getElemIndex: function(stackId) { for(var i = this.length; i--;) if(this[i].stackId == stackId) return i return -1 } }; //we check functions: objMoves.addElem({x: 2, y: 1}, 'abcdef'); objMoves.addElem({x: 3, y: 4}, 'abcdef'); objMoves.addElem({x: 5, y: 2}, 'xyz'); objMoves.addElem({x: 6, y: 2}, 'xyz'); objMoves.addElem({x: 7, y: 2}, 'xyz'); console.log(JSON.stringify(objMoves, null, '\\t')); console.log('==========================='); var index = objMoves.getElemIndex('abcdef'); objMoves.removeElem(index); console.log(JSON.stringify(objMoves, null, '\\t')); console.log('==========================='); objMoves.removeMovesElem('xyz', 1); console.log(JSON.stringify(objMoves, null, '\\t')); 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM