0

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

7
  • Could you put your expected result here? Commented Feb 21, 2022 at 7:44
  • 1
    'type' isn't a key. It's a member of an array of strings. Maybe you want to transform your data before you use it. Commented Feb 21, 2022 at 7:45
  • what happen if meta have more than two values ? Commented Feb 21, 2022 at 7:48
  • @AnhLe test should be the result Commented Feb 21, 2022 at 7:48
  • @jeremy-denis yes it will have, edited my question Commented Feb 21, 2022 at 7:49

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

meta is an array of arrays
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.