Siva Pradhan
Siva Pradhan

Reputation: 861

Find whether key starts with a particular string or not in an object and get its value?

Suppose I have an object as:

let fruitSong = {'apple song':12, 'banana song': 24}

Object.keys(fruitSong).forEach(e=>{

    if(e.startsWith('apple')){

        console.log(fruitSong[e])
    }
})

Is there any other method where I can check whether if there is any key matching with a given string, lets say 'apple' in this case should give the value?

In this case object element are very less but in case of big object object this solution will not be feasible.

Let me know if any other questions.

Upvotes: 0

Views: 101

Answers (2)

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

You can actually save half the iteration which can work well for thousands of record at-least in this case. However if there is more data, you might need to use some Data structure to achieve the task and efficiency.

const fruitSong = {'apple song':12, 'banana song': 24, 'apple song 1':12, 'banana song 1': 24, 'apple song 2':12, 'banana song 2': 24, 'apple song 3':12, 'banana song 3': 24}

const keys = Object.keys(fruitSong);

var j = keys.length -1;
var iter = 0;

for (let i = 0; i <= j;  ) {
    iter++;
    if (i == j ) {
       console.log(keys[i]);
        break;
    }

    if (j - i == 1) {
         console.log(keys[j]);
         break;
    }

    if (keys[i].includes('apple')) {console.log(keys[i]);}

    if (keys[j].includes('apple')) {console.log(keys[j]);}

    j--;
    i++
}

console.log(`Total iteration is ${iter}`);
console.log(`Total elements are ${keys.length}`);

Upvotes: 1

Paul Martin
Paul Martin

Reputation: 469

This would check to see if the key starts with 'apple'...

let fruitSong = {'apple song':12, 'banana song': 24}

const wordToCheck = "apple"

Object.keys(fruitSong).forEach(key => key.substr(0, wordToCheck.length) == wordToCheck && console.log(fruitSong[key]))

EDIT: Revised my answer to exclude regex for performance.

Upvotes: 0

Related Questions