Mathieu
Mathieu

Reputation: 4787

Create an array based on the keys of a JavaScript object

I need to create an array based on some selection of keys inside an existing constant javascript object

const EXISTING_CONSTANT_OBJECT  = {
      'fr': '10',
      'es': '15'
      'us': '10'
      'uk': '7'
      //and so on for many other iso country codes and UNPREDICTABLE key names
}

I need to be able to create an array (without modifying EXISTING_CONSTANT_OBJECT for immutability reasons) with all keys whose value are equal to 10.

For example, the expected output is

object_to_create_arr = ["fr","us"]

I tried using reduce but failed.

note: I can use ES6 and usually prefer as it's usually more concise.

Upvotes: 1

Views: 152

Answers (5)

Harshit Agarwal
Harshit Agarwal

Reputation: 2420

Object.keys() function returns the array of values corresponding to the keys of object you feed to this function. For example:

let yourObject = { key1: value1, key2: value2, key3:value3}
let arr = Object.keys(yourObject)
console.log(arr) // Output: [ 'key1', 'key2', 'key3']

Hope this helps!!

Upvotes: 0

mwilson
mwilson

Reputation: 12900

Object.keys(<object>) will do the trick BTW: Your object is invalid. You're missing some commas.

const EXISTING_CONSTANT_OBJECT = {
  'fr': '10',
  'es': '15',
  'us': '10',
  'uk': '7'
  //and so on for many other iso country codes and UNPREDICTABLE key names
};

const keys = Object.keys(EXISTING_CONSTANT_OBJECT);
console.log(keys);

If you want to just get the keys where the value is 10, it's just as simple as adding .filter

const EXISTING_CONSTANT_OBJECT = {
  'fr': '10',
  'es': '15',
  'us': '10',
  'uk': '7'
};

const keysWith10 = Object.keys(EXISTING_CONSTANT_OBJECT).filter(k => EXISTING_CONSTANT_OBJECT[k] === '10');
console.log(keysWith10);

Upvotes: 0

Martin
Martin

Reputation: 604

Try this

function createArr(obj){
    let arr = [];
    for (let key in obj) if (obj.hasOwnProperty(key) && String(obj[key]) === '10') arr.push(key);
    return arr;
}

Upvotes: 0

Neil
Neil

Reputation: 2058

You're on the right track with reduce. As mentioned with other answers, you can also use filter (which might actually be better).

Here is a solution using reduce

const obj  = {
  'fr': '10',
  'es': '15',
  'us': '10',
  'uk': '7'
}

let result = Object.keys(obj).reduce((acc, curr) => {
  if (parseInt(obj[curr], 10) === 10) {
    acc.push(curr)
  }
  return acc
}, [])

console.log(result)

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can use Object.keys and filter

const obj = { 'fr': '10','es': '15','us': '10','uk': '7'}

let final = Object.keys(obj).filter(key => +obj[key] === 10)

console.log(final)

Here + is used for implicit conversion to number, because in strict equality '10' and 10 are not same

Upvotes: 8

Related Questions