Colin747
Colin747

Reputation: 5013

JavaScript Data Not Appending to Array

I have an object of values and I am trying to populate two arrays with the keys and values from the object.

My Object:

obj = {19455746: 7476, 22489710: 473}

Loop attempting to append data:

var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
  sensorNameArray.push[i];
  sensorDataArray.push[obj[i]];
}

At the moment the two arrays are printing out as empty. My expected outout would be something like:

sensorNameArray = [19455746, 22489710];
sensorDataArray = [7476, 473];

Upvotes: 0

Views: 470

Answers (5)

ATUL SHARMA
ATUL SHARMA

Reputation: 184

Best way to deal with JSON is use lodash or underscore.

_.key() and _.value are functions for your requirement.

Eg.:

obj = {19455746: 7476, 22489710: 473};

sensorNameArray = _.keys(obj);
sensorDataArray = _.values(obj);

If you want to proceed in your way, then you can use parenthesis as push inbuilt function of Javascript for inserting element into array.

Correct is:

for(var i in obj) {
    sensorNameArray.push(i);
    sensorDataArray.push(obj[i]);
}

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26360

A different syntax (more elegant IMO) :

var sensorNameArray = Object.keys(obj)
var sensorDataArray = Object.values(obj)

or :

var sensorDataArray = sensorNameArray.map( key => obj[key] )

Upvotes: 0

Lennholm
Lennholm

Reputation: 7470

The syntax push[] doesn't invoke the function, it tries to access a property of the function object. It doesn't throw an error because in Javascript, functions ARE objects and this syntax is technically valid.

So, just fix the syntax to push() in order to actually invoke the function.

Upvotes: 0

Rahul Verma
Rahul Verma

Reputation: 398

You are using square braces [] but array.push() is a function so use circle braces instead

Try the following code

   obj = {19455746: 7476, 22489710: 473};
    var sensorNameArray = [];
    var sensorDataArray = [];
    for(var i in obj) {
      sensorNameArray.push(i);
      sensorDataArray.push(obj[i]);
    }

This is working and tested.

Upvotes: 0

Djaouad
Djaouad

Reputation: 22776

push is a function, not an array, it uses parenthesis not brackets :

for(var i in obj) {
    sensorNameArray.push(i);
    sensorDataArray.push(obj[i]);
}

Upvotes: 2

Related Questions