How to assign the result of an object breakdown to a variable that contains all unstructured fields?

Asked

Viewed 303 times

-2

Given an object x:

const x = { a: 1, b: 2, c: 3 };

and a breakdown:

const { a, b } = x;

How do I save these unstructured fields in an object that brings them together without having to:

const y = {a, b};

I tried to make

const y = { a, b } = x;

but y becomes a reference to x, that is to say, x === y results in true

Is it possible to do this at ES6? I found nothing about it in the documentation of Mozilla

const x = { a: new Date(), b: ['foo', 'bar'], c: { name: 'John' } };
const y = { a, b } = x;

console.log(x === y);

  • 1

    Reversed, the scope of the question cannot be modified after answers are presented. Create a New Question with another scope.

2 answers

5

You cannot do this. By the very name of the resource - de-structuring -, you are removing, unstructured an object. There is no way to use a "disruptor" as a tool to build other objects.

What you can do is create a function that does that for you, as a pick:

function pick(obj, props) {
  const newObj = {};
  for (const prop of props) newObj[prop] = obj[prop];
  return newObj;
}

const obj = { a: 1, b: 2, c: 3 };
console.log(pick(obj, ['a', 'c']));

It would be very interesting to have a language syntax to solve these points that are important to maintain the quality of a code and facilitate maintenance.

In this case, use Typescript or some other language. Javascript will not always guarantee you this type of security.

However, in case you are using Typescript, you can create something a little more complex that will give you the Intellisense of some editors such as Vscode:

function pick<Obj extends { [key: string]: unknown }, Props extends keyof Obj>(
  obj: Obj,
  props: Array<Props>
): { [key in Props]: Obj[key] } {
  const newObj: Pick<Obj, Props> = {} as Pick<Obj, Props>;
  for (const prop of props) newObj[prop] = obj[prop];
  return newObj;
}

const obj = { a: 1, b: 2, c: 3 };
const result = pick(obj, ['a', 'c']);
console.log(result);

See working on Typescript playground.

Or you can use libraries that already exist, like the function pick, of the Lodash, which also offers this Intellisense if you are using Typescript.

  • Thanks for the clarification. A pity that this feature is not supported natively (or will not). You think it is valid to take?

  • Luiz Felipe you can check my answer https://answall.com/a/451793/137387

  • @Luiz Felipe The only inconvenience of this solution is that the names of the unstructured variables (passed as array of strings to the pick function) cannot be accessed by the Ides' Intelli Nses and some text editors such as VS Code, for example. And that’s something I really need. The same goes for your Augustovasques solution

  • @Michaelpacheco, I edited the answer to try to get around this problem.

  • @Augustovasques, choosing properties to create a new object and choosing properties that will not be part of a new object are different things. The first of them, pick, is what I think the AP needs. The second - a kind of exclude -, which I don’t think is exactly what the AP was referring to, is something different.

  • You are mistaken, the object is created with the desired properties. It is Relational Algebra a disjoint set of what it does not want is the set of what it wants.

  • @Augustovasques, I understand your point, but selecting properties that should be added and selecting properties that should be deleted are different things. Depending on the size of the object, delete all properties to create one another with a small amount, this exclusion technique becomes impractical.

  • But then you don’t have to argue with me you have to argue with Peano’s Axioms. As for the size is not the subject of the question but the refusal of language that in the first sentence said impossible and I say it is possible.

  • @Augustovasques, I still think that "choosing" properties is different than "excluding" properties. For me, they are different things. Despite this, I understand your reply, so much so that I voted +1. :)

  • I did not negative or negative (I had not left but I left +1) because your answer is useful and works, even if I do not like the first sentence.

Show 5 more comments

3

Yes it is possible to do this in SE6.
It is an exclusion selection that combines the dismantling with a parameter Rest.

The original object will remain unchanged while the resulting object will be created with the properties of the original except those that have been unstructured.

const x = { a: new Date(), b: ['foo', 'bar'], c: { name: 'John' } };

//Enumere a as propriedades não quer de x
//No parâmetro rest restará o objeto com o que lhe é necessário. 
const {c, ...y} = x;

console.log(y);
console.log(x); // x permanece inalterado. 

  • A good suggestion but it becomes impractical when the object has many keys and the amount of unwanted fields is much higher than the desired one

  • 1

    @Michaelpacheco, but the question is not "How do you assign the result of an object structure to a variable that contains all unstructured fields?" There is the correct answer! And it is proved that yes the language allows to do.

  • Well, technically yes, but in the scenario I exemplified in the previous comment this solution becomes impractical. Imagine the case where you have an object with 1000 keys and you want to break up just 5 of them. You would list all the other 995 to get the ones you want through the Rest operator?

  • @Michaelpacheco Point out where in the question is exemplified what claims?

  • @Michaelpacheco and the question that marked as correct occurs the same problem of having to enumerate the desired properties!

  • In fact, the solution still needed to enumerate the properties and did not solve the problem in the way I would like. I removed the acceptance of the solution.

  • I do not believe that someone could have given a negative. Who negatively click on the first link I passed and read until you understand the answer.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.