Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Can't add dictionary value to an array

Let's consider the following piece of code

        var array = [];
        var obj =[{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}]
        for (x in obj){

            array.push(x.name)

        }

I end up with array which has a proper lenght but is filled with nulls. I changed this obj.name into random string and everything worked perfectly fine. It's worth to mention that the appropriate code involves angular.js and I encountered that problem when iterating over a parsed json. But even when I pasted this simple array of dictionaries called "obj", the problem was still present.

I came up that the problem must be with pushing a dictionary value into array, am I right? If yes, what is wrong?

Thanks in advance!

like image 493
theDC Avatar asked Feb 26 '26 04:02

theDC


1 Answers

The problem with your code is that, in code

for (x in obj)

x will be the index of each element in obj, meaning that instead of getting the element itself, you will get obj.indexOf(element).

In your case, x will be 0, 1. So x.name will be undefined.

Modify your code as this:

    var array = [];
    var obj =[{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}]
    for (x in obj){

        array.push(obj[x].name)

    }

and you should be good to go.

like image 107
Levi Lu Avatar answered Feb 28 '26 18:02

Levi Lu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!