javascript:如何使用push()添加JSON对象?

时间:2018-06-25 20:06:48

标签: javascript arrays object

因此,我从其他地方修改了此代码,但是有一个对象变量可在每次单击十六进制时将x,y值存储在数组中,并定义了两个函数,一个函数添加一个元素,一个函数删除最后一个元素

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);
    }

};

我这样称呼它:

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

如果我将objMoves转储到控制台日志中,结果是“ {” 0“:{” x“:2,” y“:1},” length“:1}”

但是,我真正想要的是类似

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

结果将是类似的

{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,其中将内部数组添加到给定的stackID中。我想我需要嵌套对象吗?

3 个答案:

答案 0 :(得分:0)

push()用于数组,而不是对象,因此请使用正确的数据结构。

 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;

或像对待对象一样处理它。虽然Objects不支持push属性,但也可以使用索引作为键来保存它。

答案 1 :(得分:0)

听起来您正在寻找的东西是这样的:

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);

这些函数将堆栈ID作为参数,因此可以将其用作对象的键来查找具有该ID的子对象。这些移动存储在该子对象的数组中。

答案 2 :(得分:0)

您从 MDN JavaScript reference site 中摘录的代码使我有些着迷。它向我们展示了如何将对象用作数组。所以我写了一些函数来做到这一点。

满足您所有需求的解决方案:

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'));