1

I have an object like this:

let a = { x: 3, y: '3', z: 'z' };  

And an array like this:

let b = [{ x: 1, y: '1'}, { x: 2, y: '2' }];

How can I do something like this:

b.push({ x, y } = a);

Instead of this:

b.push({ x: a.x, y: a.y });

// or this:
const { x, y } = a;
b.push({ x, y });
2
  • can be done only by creating a method or using some module like underscore b.push(_.pick(a, 'x', 'y')) Commented Dec 13, 2020 at 9:56
  • 1
    You cannot, is unfortunately the answer. Commented Dec 13, 2020 at 9:58

1 Answer 1

1

You need to return a new object with the destructured properties.

const
    getXY = ({x, y}) => ({ x, y }),
    a = { x: 3, y: '3', z: 'z' },
    b = [{ x: 1, y: '1'}, { x: 2, y: '2' }];

b.push(getXY(a));

console.log(b);

Sign up to request clarification or add additional context in comments.

1 Comment

This is a fairly common mapping pattern where you want to pass an object with some subset of keys/values to some other function. I like naming them mapTypeAToTypeB, where TypeA could be (eg) a network response with extraneous data, and TypeB could be what the frontend uses. These can be used standalone or as an Array.map() functor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.