将对象推送到对象数组javascript中的键

时间:2016-06-27 13:59:34

标签: javascript arrays javascript-objects

我有一个存储各种对象的数组。如下所示:

[ 'key2': { id: 'WA3WA9WA2WA4WAdWA1WA2WAb-WAeWAdWAaWAf-4WA1WAaWA6-WA8WA8WAeWAc-WAfWAdWAbWAeWAaWA5WA1WAfWAbWAdWAfWA2',
d: undefined,
x: 520,
y: 120 },
  'Key1': { id: 'WA7WA2WAbWAdWAfWA9WA6WA8-WA7WAdWAeWA4-4WA4WA3WAb-WAaWAdWA4WAe-WA2WAbWAdWA5WA1WA0WA7WAbWA3WAdWAfWA9',
d: undefined,
x: 810,
y: 180 } ]

如何将值推送到数组中,例如:

['key3':{id:something, d:undefined,x:200,y:400}]

这里Key1,Key2,Key3都是动态创建的并存储在变量中。

4 个答案:

答案 0 :(得分:0)

也许你的意思是你有像

这样的文字
var yourObj = { 'key1': ...
  'key2': ...
}

你要推另一个吗?如果是这样的话呢

yourObj[newKeyGenerated] = theNewObj;

答案 1 :(得分:0)

你可以有一个数组

var a = [{ id: 'WA3WA9WA2WA4WAdWA1WA2WAb-WAeWAdWAaWAf-4WA1WAaWA6-WA8WA8WAeWAc-WAfWAdWAbWAeWAaWA5WA1WAfWAbWAdWAfWA2',
d: undefined,
x: 520,
y: 120 },
{ id: 'WA7WA2WAbWAdWAfWA9WA6WA8-WA7WAdWAeWA4-4WA4WA3WAb-WAaWAdWA4WAe-WA2WAbWAdWA5WA1WA0WA7WAbWA3WAdWAfWA9',
d: undefined,
x: 810,
y: 180 } ]

在这种情况下a.push({...})

或对象

var a = { 'key2': { id: 'WA3WA9WA2WA4WAdWA1WA2WAb-WAeWAdWAaWAf-4WA1WAaWA6-WA8WA8WAeWAc-WAfWAdWAbWAeWAaWA5WA1WAfWAbWAdWAfWA2',
d: undefined,
x: 520,
y: 120 },
  'Key1': { id: 'WA7WA2WAbWAdWAfWA9WA6WA8-WA7WAdWAeWA4-4WA4WA3WAb-WAaWAdWA4WAe-WA2WAbWAdWA5WA1WA0WA7WAbWA3WAdWAfWA9',
d: undefined,
x: 810,
y: 180 } }

然后你可以拥有a.key3 = {...}

答案 2 :(得分:0)

如果我理解正确,这应该是解决方案:https://jsfiddle.net/a7uxd4tk/

var data1 = [ {'key1': { id: 'a', d: undefined, x: 520, y: 120 }}];
var data2 =  [ {'key2': { id: 'b', d: undefined, x: 520, y: 120 }}];
var data3 =  [ {'key3': { id: 'b', d: undefined, x: 520, y: 120 }}];
var addData = [];
addData.push(data1[0]);
addData.push(data2[0]);
addData.push(data3[0]);
console.log(addData);

另请注意[ {} ]

答案 3 :(得分:0)

试一试:

var data = [ {'key2': { id: 'WA3WA9WA2WA4WAdWA1WA2WAb-WAeWAdWAaWAf-4WA1WAaWA6-WA8WA8WAeWAc-WAfWAdWAbWAeWAaWA5WA1WAfWAbWAdWAfWA2',
d: undefined,
x: 520,
y: 120 }},
  {'Key1': { id: 'WA7WA2WAbWAdWAfWA9WA6WA8-WA7WAdWAeWA4-4WA4WA3WAb-WAaWAdWA4WAe-WA2WAbWAdWA5WA1WA0WA7WAbWA3WAdWAfWA9',
d: undefined,
x: 810,
y: 180 }} ];

var newObj = {};
newObj.key3 = {};

newObj.key3.id = 'WA3WA9WA2WA4WAdWA1WA2WAb-WAeWAdWAaWAf-4WA1WAaWA6-WA8WA8WAeWAc-WAfWAdWAbWAeWAaWA5WA1WAfWAbWAdWAfWA2';
newObj.key3.d = undefined;
newObj.key3.x = 520;
newObj.key3.y= 120;

data.push(newObj);
console.log(data);