-2

I have below JSON return as response from API:

{"data":"123","value":[{name:'test", class:"A1"},{name:'test2", class:"A2"},{name:'test", class:"A3"}]}

I want to access name & class property of value array. I tried:

myArray.forEarch((element, index, array) => {

})

but this does not work well. Any pointer please.

Thankk

Carlos
  • 331
  • 6
  • 14
Dev Developer
  • 115
  • 2
  • 13
  • 3
    `myArray.forEarch` Spelling matters in programming. What is `myArray`? is that the object in your first code? (It's an object, not an array) – CertainPerformance Dec 02 '19 at 08:49
  • Assuming the response is parsed into an object (and is actually proper JSON, not the single quote mess in your question) and stored in `obj`, you need `obj.value.forEach((element, index) => { ... });` –  Dec 02 '19 at 08:49
  • 1
    The response also looks to be invalid JSON, it won't parse - the brackets are mismatched, and `'` string delimiters are forbidden in JSON (you must always use `"`) – CertainPerformance Dec 02 '19 at 08:50
  • my bad, but looks like I did that mistake as typo,thanks for pointing out anyways. – Dev Developer Dec 02 '19 at 08:53

2 Answers2

0

You can do it with a foreach like that.

const data = {'data':'123','value':[{'name':'test', 'class':'A1'},{'name':'test2', 'class':'A2'},{'name':'test', 'class':'A3'}]}



data.value.forEach(function (el){ 
  console.log(el.name);
  console.log(el.class);
});
Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
-1

Try this...

const jsonData = JSON.parse( ... );

for (const obj of jsonData.values) {
    const name = obj.name;
    const _class = obj.class;

    // Use name and _class
}
Kwame Opare Asiedu
  • 2,110
  • 11
  • 13