Home > other >  Returns keys as string of an Array of Objects
Returns keys as string of an Array of Objects

Time:04-08

I have an array of objects and I need the keys of all objects that appear in this array. I work with Google Tag Manager templates and this uses a Sandboxed version of JavaScript. Therefore, some functions, like RegEx, are not present.

My array:

var products: [{
        'name': 'Test Product 1',         
        'variant': 'Blue'
       },
       {
        'name': 'Test Product 2',         
        'id': '12345',
        'price': '15.25',
       }]

As you can see, some keys are present for product 1 but not for product 2. This is works as attended. Whenever one key is present here, we want that key back as a (list of) strings. I'm trying to create the following:

'name, id, variant, price'

I've tried converting the array to a string. However, this makes the array messy. And since .replace() doesn't always work and RegEx is not present it's hard to clean the string.

This happens when I convert the array to a string.


var arrayToString = JSON.stringify(ourArray);

//output "[\\"id","name"\"\]"

Any suggestions for my issue?

CodePudding user response:

You can simply flatMap the Object.keys() into a Set which can be converted back to an array, here using spread syntax (...)

const products = [{ 'name': 'Test Product 1', 'variant': 'Blue' }, { 'name': 'Test Product 2', 'id': '12345', 'price': '15.25', }]

const keys = [...new Set(products.flatMap(Object.keys))];

console.log(keys.join(', '))

CodePudding user response:

Try this

const products =  [{
    'name': 'Test Product 1',
    'variant': 'Blue'
  },
  {
    'name': 'Test Product 2',
    'id': '12345',
    'price': '15.25',
  }
]


const keys = products.reduce((res, p) =>  [...res, ...Object.keys(p)], [])

const keyString = [...new Set(keys)].join(', ')

console.log(keyString)

CodePudding user response:

It's a straight forward solution. Just loop over the object's keys

var products = [{
        'name': 'Test Product 1',         
        'variant': 'Blue'
       },
       {
        'name': 'Test Product 2',         
        'id': '12345',
        'price': '15.25',
       }]
const keys = []
products.forEach(obj => {
  for(item in obj){
    if(!keys.includes(item)){
      keys.push(item)
    }
  }
})
let result = keys.join(', ')
console.log(result)

CodePudding user response:

var products = [{
        'name': 'Test Product 1',         
        'variant': 'Blue'
       },
       {
        'name': 'Test Product 2',         
        'id': '12345',
        'price': '15.25',
       }]
const keys = []
products.forEach(obj => {
  for(item in obj){
    if(!keys.includes(item)){
      keys.push(item)
    }
  }
})
const output = keys.join(', ')
console.log(output)

  • Related