gclark18
gclark18

Reputation: 725

Access values within a JSON object using Javascript

I have a JSON object (of objects) that firefox tells me looks like this:

Object(8)
​0: Object { name: "Appleby", value: 8670, line_count: 4, … }
​1: Object { name: "Armthorpe", value: 1470, line_count: 3, … }
​2: Object { name: "Blackbrook", value: 300, line_count: 2, … }
​3: Object { name: "Blackpool", value: 600, line_count: 1, … }

I would like to extract two arrays from this, a list of the names and values, such as:

myArray['names'] = ["Appleby", "Armthorpe", ...]
myArray['values'] = [8670, 1470, ...]

Can you please advise how I can do this?

I have tried using this for in loop:

for(const item in input) 
{
myArray.names.push(item.name); 
myArray.values.push(item.value);
}

However, this returns only integers, and not the objects, as shown in this console output:

> input = {0: { name: "Appleby", value: 8670, line_count: 4, }, 1:{ name: "Armthorpe", value: 1470, line_count: 3, }, 2: { name: "Blackbrook", value: 300, line_count: 2 }, 3: { name: "Blackpool", value: 600, line_count: 1,}}
< {0: {…}, 1: {…}, 2: {…}, 3: {…}}
> let myArray = {names: [], values: []}
< undefined
> for(const item in input) {myArray.names.push(item.name); myArray.values.push(item.value);}
< 4
> myArray
< {names: Array(4), values: Array(4)}

Upvotes: 0

Views: 59

Answers (1)

Moshe
Moshe

Reputation: 2674

Pass in your object of objects as inputObject and use this function:

/**
* This function converts a JSON object of objects into two separate arrays:
* 1. names 
* 2. values
*/
function myFunction(inputObject) {

  const myArray = { // should be myObject, really.
    names: [],
    values: []
  };


  for(const item of inputObject) {
    myArray.names.push(item.name);
    myArray.values.push(item.value);
  }

  return myArray;
}

Upvotes: 1

Related Questions