'Trying to return values with their key name from nested JSON array

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



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 uminder
Solution 2 TalESid