1

Is there a way I can destructure object into its arbitrary property value and the rest of the properties?

So far, my attempts didn't give much success:

const x = {a:1, b:2, c:3};
const obj2pieces = (obj,propName) => {
    ({propName,...rest} = obj);
    return [propName, {...rest}]
};
console.log(obj2pieces(x, 'a')); // [undefined,{"a":1,"b":2,"c":3}]

What I would like to get instead is [1,{"b":2,"c":3}].

  • Use bracket notation, just like when assigning or looking up a variable in a property. `const {[propName]: val,...rest} = obj;` and `return [val, rest]` (no need to spread `rest`there) – CertainPerformance Aug 09 '19 at 07:40

1 Answers1

0

You need a computed property name and a renaming for the extracting value.

const
    x = { a: 1, b: 2, c: 3},
    obj2pieces = (obj, propName) => {
        const {[propName]: temp, ...rest } = obj;
        return [temp, rest]
    };

console.log(obj2pieces(x, 'a'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392