j_d
j_d

Reputation: 3082

Trouble reformatting JSON into an array for use in AngularJs

Js has a built-in parse function which I am using: JSON.parse. It's the reformatting I'm having trouble wrapping my head around. Eg if I want to fetch all stars from the NASA API as JSON. This gives me a massive list of all the stars, with one entry looking like this:

{
    "absmag": 4.85, 
    "appmag": -26.72, 
    "colorb_v": 0.65, 
    "created_at": "2014-11-08T07:30:49.614Z", 
    "dcalc": 0.0, 
    "distly": 0.0, 
    "hipnum": 0.0, 
    "id": 1, 
    "label": "Sun", 
    "lum": 0.8913, 
    "plx": 0.0, 
    "plxerr": 0.0, 
    "speed": 0.0, 
    "texnum": 1.0, 
    "updated_at": "2014-11-08T07:30:49.614Z", 
    "vx": 0.0, 
    "vy": 0.0, 
    "vz": 0.0, 
    "x": 0.0, 
    "y": 0.0, 
    "z": 0.0
}

I then strip out just the "label" value for searching:

window.database.forEach(function(el) {
            var starNameArray = el.label;
        })

Which gives me a plain list of just the star labels. I need to convert this list to this form:

[ 'thing1', 'thing2', 'thing3' ]

I attempt to use something like this:

console.log("'" + starNameArray.join("','") + "'");

But I get the error: "Uncaught TypeError: starNameArray.join is not a function"

Any idea why? Am I making a stupid mistake somewhere along the line here?

Upvotes: 1

Views: 44

Answers (3)

hubson bropa
hubson bropa

Reputation: 2770

looks like you are declaring starNameArray inside the foreach and setting starNameArray to el.label, so its a string based on you JSON example. Also its scope is only inside the foreach so assuming your console.log is outside that function, and its not declared elsewhere, starNameArray would be undefined. @edrain just posted the code that fixes these issues.

Upvotes: 0

Roy James Schumacher
Roy James Schumacher

Reputation: 646

based on the code you provided starNameArray is just storing a string value have you tried creating an array and then pushing each label into the array like,

var starNameArray = [];
window.database.forEach(function(el){
     starNameArray.push(el.label);
})

after doing this you will have an array of the elements.

the join method will create a string of your elements rather than and actual array.

Upvotes: 0

edrian
edrian

Reputation: 4531

var starNameArray = [];
window.database.forEach(function(el) {
   starNameArray.push(el.label);
});
console.log(starNameArray.join(","));

Upvotes: 1

Related Questions