Home > Net >  Get value by key from array of array - Javascript
Get value by key from array of array - Javascript

Time:02-21

I have a meta as below:

obj = {
   meta: [['type', 'test1'], ['key2', 'value2']],
   value: 'text1',
}

Want to read value test by passing the key type

expected result is test1

CodePudding user response:

You could use Object.fromEntries()

const obj = {
   meta: [['type', 'test'], ['key2', 'value2']],
   value: 'text1',
}

const key = 'type'

const res = Object.fromEntries(obj.meta)[key];

console.log(res)

CodePudding user response:

You should restructure meta as an object instead of an array of pairs as:

obj = {
   meta: {
        'type': 'test',
        'key2': 'value2'
   }
   value: 'text1',
}

Now, you can access what you need as obj['meta']['type'] or obj.meta.type.

CodePudding user response:

obj = {
   meta: [['type', 'test'], ['key2', 'value2']],
   value: 'text1',
}

  for(let arr of obj.meta){
      if(arr[0]==='type'){
        return arr[1];
    }
 }

or

const res=obj.meta.find(arr=>arr[0]==="type");
if(res && res.length) return res[1]

Notice that this code returns only the first "type". If you have "type" twice you'll get the first result.

  • Related