Get element from json array javascript

22,164

Solution 1

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));
});

Solution 2

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);
});

Solution 3

Use JSON.parse, and use map:

const data = [{
  "assetName": "LCT",
  "assetValue": "",
  "typeValueInput": "select",
  "valueInputSelect": null,
  "required": true,
  "valueInput": "{\"data\":[{\"name\":\"name1\",\"id\":\"12\"},{\"name\":\"name2\",\"id\":\"13\"},{\"name\":\"name3\",\"id\":\"14\"}]}"
}]
const names = JSON.parse(data[0].valueInput).data.map(({ name }) => name);
console.log(names);

Share:
22,164
Java Dev Beginner
Author by

Java Dev Beginner

Updated on July 09, 2022

Comments

  • Java Dev Beginner
    Java Dev Beginner almost 2 years

    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!

  • R3tep
    R3tep about 5 years
    @Deepakgupta data[0] is not a string, the array is parsed before. See the live demo before post a comment
  • AZ_
    AZ_ about 5 years
    the input value is a string, not an object, and the string is not correctly stringified.
  • R3tep
    R3tep about 5 years
    @AZ_ The input value is not a string. Jack make some bad edit
  • AZ_
    AZ_ about 5 years
    it says I have a simple Json String not sure maybe.
  • R3tep
    R3tep about 5 years
    @AZ_ Yes he have a json string into the key valueInput