javascript assign variable to key-values extracted from object

Viewed 34

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",
}
4 Answers

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 });

You can try it:

const {id, img, name} = BigObject;
const User = {id, img, name};

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)

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)
Related