0

I'm working on something like this:

my object looks like that:

{
  a: 1,
  b: 2,
  c: 3,
  game01: 1,
  game02: 2,
  game03: 3
}

what I need to do is to return from it an object containing only last 3 pairs so it'd look like that:

{
  game01: 1,
  game02: 2,
  game03: 3
}

I would prefer not to do that manually but it'd be the best to use a something similar as filtering an array.

Thanks!

Tholle
  • 108,070
  • 19
  • 198
  • 189
Murakami
  • 3,474
  • 7
  • 35
  • 89

4 Answers4

1

There is no real concept of order in an object, so you can't reliably extract the "last three keys" of an object.

However, you could loop over all the keys in the object and only include the ones that have game as a substring in your final result.

Example

const obj = {
  a: 1,
  b: 2,
  c: 3,
  game01: 1,
  game02: 2,
  game03: 3
};

const result = Object.keys(obj).reduce((result, key) => {
  if (key.includes('game')) {
    result[key] = obj[key];
  }
  return result;
}, {});

console.log(result);
Tholle
  • 108,070
  • 19
  • 198
  • 189
0

you can iterate over object with Object.keys and then slice last 3 keys and create a new object out of old.

var test = {
    a: 1,
    b: 2,
    c: 3,
    game01: 1,
    game02: 2,
    game03: 3
    }
    var newObject = {};
    Object.keys(test).slice(-3).forEach(ele=>newObject[ele] = test[ele]);
    console.log(newObject)
Manoj
  • 1,175
  • 7
  • 11
0

You could define your own filter method, for instance on Object, so that it works a bit like Array#filter:

Object.from = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
Object.filter = (obj, predicate) => Object.from(Object.entries(obj).filter(predicate));

// Example use:
const obj = {a: 1, b: 2, c: 3, game01: 1, game02: 2, game03: 3 };

const filtered = Object.filter(obj, ([key, value]) => key.includes("game")); 
console.log(filtered);

As you see there is also another method I defined here, which can be useful on its own: Object.from creates an object from an array that has key/value pairs (sub arrays). It does the opposite as Object.entries does, which creates an array of key/value pairs for a given object.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

You could turn the existing object into an array of arrays (with each element-array contains [key,value]) using Object.entries(obj) and then loop through that to check if each key contains the "game" substring. You can add the ones that meet this criteria into some new object.

let obj = {
    a: 1,
    b: 2,
    c: 3,
    game01: 1,
    game02: 2,
    game03: 3
    };

let substring="game";
let key_value_pairs = Object.entries(obj);
let newObj = {};

key_value_pairs.forEach(element => {
    if(String(element[0]).includes(substring)){
        newObj[element[0]] = element[1];    
    }
}); 
//newObj will now be {game01: 1, game02: 2, game03: 3}
Herbert Su
  • 41
  • 3