[英]javascript assign variable to key-values extracted from object
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其中用户将是 object 之类的
{
"id":"value",
"img":"value",
"name":"value",
}
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 ofuser
."“类似...
const user = (({ id, img, name }) => ({ id, img, name }))(BigObject);
... 的方法基于立即调用的箭头 function创建user
后不再需要的本地引用。”
Implementing the solution with an arrow function might also come closest to the OP'S original intention...用箭头 function 实现解决方案也可能最接近 OP 的初衷......
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 eg `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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.