简体   繁体   中英

Return a key of an object based on value of an array

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

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 .

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]) } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM