0

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];
4
  • 6
    Your syntax is incorrect, it should be push(), not push[] Commented Aug 9, 2017 at 10:27
  • haha thanks, don't know how I didn't spot that. All working now. Commented Aug 9, 2017 at 10:28
  • @MikaelLennholm if you want to add that comment as an answer I'll accept. Commented Aug 9, 2017 at 10:29
  • Alright, will do! Commented Aug 9, 2017 at 10:32

5 Answers 5

2

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

for(var i in obj) {
    sensorNameArray.push(i);
    sensorDataArray.push(obj[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

A different syntax (more elegant IMO) :

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

or :

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

Comments

0

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

2 Comments

This isn't JSON
Ya I'm just suggesting other ways, to access objects, so it might be helpful in future. Correction of current code is also specified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.