0

I have an array that stores various objects. Looks like following:

[ '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 } ]

How do I push a value into the array such as:

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

Here Key1, Key2, Key3 are all dynamically created and stored in a variable.

Arihant
  • 3,847
  • 16
  • 55
  • 86
  • 5
    That is invalid. Either you have an array or you have an object with keys, – str Jun 27 '16 at 14:01
  • 1
    Possible duplicate of [Adding items to an object through the .push() method](http://stackoverflow.com/questions/7261431/adding-items-to-an-object-through-the-push-method) – str Jun 27 '16 at 14:03

4 Answers4

0

maybe You mean You have a literal like

var yourObj = { 'key1': ...
  'key2': ...
}

and You want to push another one? if it's the case do it

yourObj[newKeyGenerated] = theNewObj;
fedeghe
  • 1,243
  • 13
  • 22
0

You can have an array

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 } ]

in this case a.push({...})

or an object

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

and then you can have a.key3 = {...}

Carlo
  • 2,103
  • 21
  • 29
0

If I have understood correctly , this should be the solution : 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);

Also do note [ { and } ]

Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
0

Try it:

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);
msantos
  • 691
  • 5
  • 6