Home > other >  Extract only key names from JSON in array format using nodejs
Extract only key names from JSON in array format using nodejs

Time:11-23

How to get JSON data key names in a array format using nodejs?

I've tried the following but it returns object. But I want an array so I can store it in a varaible.

const jsondata = [{ "name": "StorageType", "value": "AllStorageTypes" }, { "name": "BucketName", "value": "testing" }]

Object.keys(jsondata).forEach(function(key) {
  var value = jsondata[key];
  console.log(value)
});

output:

{ name: 'StorageType', value: 'AllStorageTypes' }
{ name: 'BucketName', value: 'testing' }

Expected output:

["StorageType", "BucketName"]

CodePudding user response:

Try this

const jsondata = [{ "name": "StorageType", "value": "AllStorageTypes" }, { "name": "BucketName", "value": "testing" }]

const arrayData = jsondata.map(item => item.name)
console.log(arrayData)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

jsondata.map(obj=>obj.name)

  • Related