Skip to content Skip to sidebar Skip to footer

Clone A Object Json But Until Its 5th Key-value

I have a JSON that has more than 10 key-values, I need to create a copy of this but limiting it until the 5th key-value. Input: var object1 = { '1a': 1, '2b': 2, '3c': 1,

Solution 1:

You could slice the array of entries and rebuild a new object with Object.fromEntries.

var object = { "1a": 1, "2b": 2, "3c": 1, "4d": 2, "5e": 1, "6f": 2, "7g": 1, "8h": 2, "9i": 1, "10j": 2 },
    result = Object.fromEntries(Object.entries(object).slice(0, 5));
    
console.log(result);

The same with Object.assign.

var object = { "1a": 1, "2b": 2, "3c": 1, "4d": 2, "5e": 1, "6f": 2, "7g": 1, "8h": 2, "9i": 1, "10j": 2 },
    result = Object.assign({}, ...Object
        .entries(object)
        .slice(0, 5)
        .map(([k, v]) => ({ [k]: v }))
    );
    
console.log(result);

Solution 2:

You could easily use something like this, it's a relatively standard implementation by making use of the reduce method.

What's good about this solution is that it's so simple that even beginners can make sense of it.

var object1 = {
  "1a": 1,
  "2b": 2,
  "3c": 1,
  "4d": 2,
  "5e": 1,
  "6f": 2,
  "7g": 1,
  "8h": 2,
  "9i": 1,
  "10j": 2
};

var object2 = Object.keys(object1).reduce((o, k, i) => {
  i < 5 ? o[k] = object1[k] : null;
  return o;
}, {});

console.log(object2);

Post a Comment for "Clone A Object Json But Until Its 5th Key-value"