0

How to get key1 by using uniquevalue1 from the following object? If that's possible, how to get key by othervalues in 'an array'?

{ 'key1': { anarray: ['othervalues '], value: 'uniquevalue1' }, 'key2': { value: 'uniquevalue2', anarray: ['othervalues '] } } 

3 Answers 3

1

You could .find a key-value pair:

 const [key] = Object.entries(input) .find(([, { value }]) => value === "uniquevalue1"); 
Sign up to request clarification or add additional context in comments.

Comments

0

Here's an example on how you can find the key by value.

let arr = { 'key1': { anarray: [ 'othervalues ' ], value: 'uniquevalue1' }, 'key2': { value: 'uniquevalue2', anarray: [ 'othervalues ' ] }} const findKeyByValue = (val) => { for(const key in arr) { if(arr[key].value.includes(val)) return key; } }; console.log(findKeyByValue('uniquevalue1'));

Comments

0

Matches the value which is a string or inside an array

function getKeyByValue(_json, searchValue, searchInArray=false) { for (const [key,val] of Object.entries(_json)) { const {anarray, value} = val; if (searchInArray && anarray.includes(searchValue)) { return key; } else if (searchValue === value) { return key; } } } var data = { 'key1': { anarray: ['othervalues'], value: 'uniquevalue1' }, 'key2': { value: 'uniquevalue2', anarray: ['othervalues'] } }; console.log(getKeyByValue(data, 'uniquevalue1')); console.log(getKeyByValue(data, 'othervalues', true));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.