Home > Back-end >  Trying to return values with their key name from nested JSON array
Trying to return values with their key name from nested JSON array

Time:04-19

I am trying to return values with their key name from nested JSON array

resData =[
  {
    _index: 'web',
    _type: 'event',
    _id: 'web 0 93',
    _score: null,
    _source: {
      'os-name': 'Windows',
      'browser-version': '90.0',
      'os-version': '10',

    },
    sort: [ '20210729T05:48:03Z' ]
  }
]
resData[0]._source["os-name"=>"os-name", 'browser-version'=>'90.0', 'browser-version': '90.0'];

but giving this error

SyntaxError: Malformed arrow function parameter list

Expected Output:

'os-name': 'Windows',
'browser-version': '90.0',
'os-version': '10'

i also tried .map but it also did not worked because of my '-hyphen ' between variable name

CodePudding user response:

This can be done as follows:

const resData =[
  {
    _index: 'web',
    _type: 'event',
    _id: 'web 0 93',
    _score: null,
    _source: {
      'os-name': 'Windows',
      'browser-version': '90.0',
      'os-version': '10'
    },
    sort: [ '20210729T05:48:03Z' ]
  }
];

const result = Object.entries(resData[0]._source)
                  .map(e => e[0]   ': '   e[1])
                  .join('\n');

console.log(result);

CodePudding user response:

const resData = [
  {
    _index: 'web',
    _type: 'event',
    _id: 'web 0 93',
    _score: null,
    _source: {
      'os-name': 'Windows',
      'browser-version': '90.0',
      'os-version': '10'
    },
    sort: [ '20210729T05:48:03Z' ]
  }
];

const output = Object.entries(resData[0]['_source'])
                     .map(([key, value]) => `${key}: ${value}`)
                     .join(',\n');

console.log(output);

  • Related