0

So I have Json obj which I convert via JSON.stringfy and the result is:

{
  "data" : [ {
    "id" : 417206355511802,
    "name" : "test01"
  }, {
    "id" : 421211003974634,
    "name" : "test02"
  }, {
    "id" : 403713622404901,
    "name" : "test03"
  }]
}

How can I access each name value? I was trying:

var test = result[0].name; alert(test);

0

2 Answers 2

1

You can't access anything from the result of stringify() - it produces a string, hence its name. Rather, it sounds like you started with a string and converted it to an object via JSON.parse().

If that's not the case, and you already have the object, you don't need to stringify if you want to access properties.

That out of the way, you're missing the data step.

myobj.data[0].name; //<-- where myobj is the variable holding the object
Sign up to request clarification or add additional context in comments.

4 Comments

so it should be: var test = data[0].name; alert(test); ?
It should be myobj.data[0].name, where myobj is the variable the object is stored in, whatever you've called it.
I have related question, so I'll try here instead of creating new question. Is it possible to count elements "name" in this object withour for loop?
Well surely that's the same as asking how many elements are in the array, since all elements have a name property. In which case, myobj.data.length
0

JSON.stringify will not help you.becouse it's give a string as output.you can directly access the object elements by

var arr = myObj.data;
arr.forEach(function(elem)     { 
      console.log(elem.id);
      console.log(elem.name);
});

Comments

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.