-2

how can i do something like the following

const BigObject = {
"id":"value",
"img":"value",
"name":"value",
"otherData":"value",
"otherData":"value",
"otherData":"value",
"otherData":"value",

}
var User = {id,img,name} = BigObject

where User will be an object like

{
    "id":"value",
    "img":"value",
    "name":"value",
}
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Abd
  • 497
  • 4
  • 14
  • Does this answer your question? [How to get a subset of a javascript object's properties](https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties) – DBS Sep 20 '22 at 09:30
  • An approach like ... `const user = (({ id, img, name }) => ({ id, img, name }))(BigObject);` ... which is based on an immediately invoked arrow function prevents additional local references which are not needed anymore after the creation of `user`. – Peter Seliger Sep 20 '22 at 09:35

4 Answers4

2

From my above comment ...

"An approach like ... const user = (({ id, img, name }) => ({ id, img, name }))(BigObject); ... which is based on an immediately invoked arrow function prevents additional local references which are not needed anymore after the creation of user."

Implementing the solution with an arrow function might also come closest to the OP'S original intention ...

const bigObject = {
  id: 'value',
  img: 'value',
  name: 'value',
  otherData: 'value',
};

// OP ...how can i do something like the following?..
//
// const user = { id, img, name } = bigObject

// prevent additional module or global
// scope of e.g. `id`, `img`, `name`.
const user = (({ id, img, name }) => ({ id, img, name }))(bigObject);

console.log({ user });
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
0

You can try it:

const {id, img, name} = BigObject;
const User = {id, img, name};
tieulinh
  • 21
  • 3
0

You could do it like below:

const BigObject = {
 "id":"value",
 "img":"value",
 "name":"value",
 "otherData":"value",
 "otherData":"value",
 "otherData":"value",
 "otherData":"value"
}
let {id, img, name, ...rest} = BigObject;
let User = {id,img,name};
console.log(User)
kavigun
  • 2,219
  • 2
  • 14
  • 33
0

you can do something like this

const BigObject = {
"id":"value",
"img":"value",
"name":"value",
"otherData":"value",
"otherData":"value",
"otherData":"value",
"otherData":"value",

}
let {id,img,name} = BigObject
const User = {id,img,name}
console.log(User)
Aman Kumar
  • 121
  • 4