-1

I want to ask if I have an object like this

const dataArray = {
    key1: ["a", "b"],
    key2: ["c", "d"],
    key3: ["e", "f"],
};

I tried

    const obj = Object.keys(dataArray).map((data, index) => {
        return dataArray[data];
        if (dataArray[data].indexOf("water") > -1) {
            return Object.keys(dataArray);
        }
    });

I want to return a key (key1, key2, key3) that has values of the string "c".

How do I do that? please help

Goacgras
  • 11
  • 1
  • 1
    you can do it one liner `console.log(Object.keys(dataArray).find(k => dataArray[k].includes("c")));` – D. Seah Jan 19 '21 at 03:17
  • Pretty close to [this question](https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value), just needs to be adapted to search array values – Phil Jan 19 '21 at 03:22

2 Answers2

4

You should know a difference about .map, .find, .filter

const dataArray = {
    key1: ["a", "b"],
    key2: ["c", "d"],
    key3: ["e", "f"],
};
const result1 = Object.keys(dataArray).map((data, index) => {
        return dataArray[data];
        // The line below do not affect !!!
        if (dataArray[data].indexOf("water") > -1) {
            return Object.keys(dataArray);
        }
    });
console.log(result1.join(',')); // All records from `dataArray`

/*******Find one item => using find*/
console.log(Object.keys(dataArray).find(k => dataArray[k].includes("c")));

/*******Find multiple items => using filter*/
console.log(Object.keys(dataArray).filter(k => dataArray[k].includes("c") || dataArray[k].includes("e")));

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

  • @Goacgras Does this answer your question? Let me know if you need any help https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –  Jan 29 '21 at 08:44
0

You can get the entries of the object (key / value pairs) and iterates to get your desired key (if value includes 'c')

const dataArray = {
    key1: ["a", "b"],
    key2: ["c", "d"],
    key3: ["e", "f"],
};

const entries = Object.entries(dataArray);

for(let entry of entries){
    if(entry[1].includes('c')){
        console.log(entry[0])
    }
}
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35