简体   繁体   English

如何在javascript中将所有属性破坏为本地let

[英]How to destruct all properties as local let in javascript

say i have a object : 说我有一个对象:

const ob = { a : 1, b : 'hello world', c : 3, d : false, e : { zn : 'nested value' }};

I want a one liner, preferably using destructing to grab 5 new variables in local scope. 我想要一个衬板,最好使用销毁方法在本地范围内获取5个新变量。

//do something with ob
//now i want to have 5 const/let defined in local scope
// such as, a =1, b = 'hello world', c = 3, d = false, e = { zn : 'nested value' }

EDIT1 : i have long key properties and there is 10 properties that i want to use all of them, directly without any dot, and i find writing 10 lengthy variable names boring.. EDIT1:我有很长的键属性,并且我想直接使用10个属性,而没有任何点,并且我发现写10个冗长的变量名很无聊。

It is as simple as wrapping your desired identifiers in an object-style syntax 就像用对象样式的语法包装所需的标识符一样简单

const {a, b, c, d, e} = {a: 1, b: 'hello world', c: 3, d: false, e: {zn: 'nested value'}};
a; // 1
b; // "hello world"
// etc

Note you can also go into arrays or go deeper into nests if needed; 注意,如果需要,您也可以进入数组或进入嵌套。

const [{f: {g}}] = [{f: {g: 1}}];
f; // undefined
g; // 1

Further, you can rename identifiers during destructring 此外,您可以在销毁期间重命名标识符

const {old: now} = {old: 1};
old; // undefined
now; // 1

Well if you want to shorten and assign them to a variable, one way is to use eval. 好吧,如果要缩短它们并将其分配给变量,一种方法是使用eval。

But then again, why do you need to create them as variables? 但是话又说回来,为什么需要将它们创建为变量?

 const ob = { a : 1, b : 'hello world', c : 3, d : false, e : { zn : 'nested value' }}; var i = 0; for (let key in ob) { eval(`var index${i} = "${ob[key]}"`); i++; } console.log(index0); console.log(index1); console.log(index2); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM