Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element from json array javascript [closed]

I have a simple Json String

[
   {
      "assetName":"LCT",
      "assetValue":"",
      "typeValueInput":"select",
      "valueInputSelect":null,
      "required":true,
      "valueInput":"{\"data\":[{\"name\":\"name1\",\"id\":\"12\"},{\"name\":\"name2\",\"id\":\"13\"},{\"name\":\"name3\",\"id\":\"14\"}]}"
   }
]

I want get field Name in Data in ValueInput by Javascript.

Please help me!

like image 687
Java Dev Beginner Avatar asked Mar 25 '19 08:03

Java Dev Beginner


2 Answers

You need to loop through the array and then parse the stringified JSON so that you can access the data array. Then simply loop that data array to get the value of each name property.

var arr = [{
  "assetName": "LCT",
  "assetValue": "",
  "typeValueInput": "select",
  "valueInputSelect": null,
  "required": true,
  "valueInput": "{\"data\":[{\"name\":\"name1\",\"id\":\"12\"},{\"name\":\"name2\",\"id\":\"13\"},{\"name\":\"name3\",\"id\":\"14\"}]}"
}];

arr.forEach((arrObj) => {
  var jsonData = JSON.parse(arrObj.valueInput);
  jsonData.data.forEach(({name}) => console.log(name));
});
like image 130
Ankit Agarwal Avatar answered Sep 19 '22 01:09

Ankit Agarwal


You could use JSON.parse

var jsonArray = [
  {
    assetName: 'LCT',
    assetValue: '',
    typeValueInput: 'select',
    valueInputSelect: null,
    required: true,
    valueInput:
      '{"data":[{"name":"name1","id":"12"},{"name":"name2","id":"13"},{"name":"name3","id":"14"}]}'
  }
];

let name = jsonArray[0].valueInput;
name = JSON.parse(name);
name.data.forEach(value => {
  console.log(value.name, value.id);
});
like image 23
Loc Mai Avatar answered Sep 21 '22 01:09

Loc Mai