[英]how to destruct a key pair object
I'm trying to destruct a map object with one single [key, value]
pair, as example:我正在尝试使用一对
[key, value]
来破坏map object,例如:
var v = { foo: 'bar'};
function f({key, value}) {
console.log('key is ' + key);
console.log('value is ' + value);
}
f(v);
This example should print:这个例子应该打印:
key is foo
value is bar
but it's actually printing:但它实际上正在打印:
key is undefined
value is undefined
How can I achieve this?我怎样才能做到这一点? Note: key names can vary.
注意:键名可以不同。
Not sure you can destructor key / values directly inside the parameters. 不确定是否可以在参数内部直接销毁键/值。
But you could do it inside the function.. 但是您可以在函数内部完成此操作。
eg. 例如。
const v = { foo: 'bar'}; function f(o) { const [key, value] = Object.entries(o)[0]; console.log('key is ' + key); console.log('value is ' + value); } f(v);
Not sure this is what you're looking for, but Object.keys()
does do the trick. 不确定这不是您要查找的内容,但是
Object.keys()
确实可以解决问题。
var v = { foo: 'bar'}; function f(o) { console.log('key is ' + Object.keys(o)[0]); console.log('value is ' + o[Object.keys(o)[0]]); } f(v);
You could use Object.entries
for getting the entries of the object, which returns a key value array for each entry. 您可以使用
Object.entries
获取对象的条目,这将为每个条目返回一个键值数组。
function f(object) { for (var [key, value] of Object.entries(object)) { console.log('key is ' + key); console.log('value is ' + value); } } f({ foo: 'bar' });
This should work for objects with multiple properties too. 这也应适用于具有多个属性的对象。
var object = { foo: 'bar', food: 'pizza'}; function f(object) { // get an array of all keys let keys = Object.keys(object); // iteratate over this array keys.forEach(key => { // output the current key and associated value let property = object[key]; console.log('key is ' + key); console.log('value is ' + property); }); } f(object);
var v = { foo: 'bar'}; function f(obj) { var pair = Object.entries(obj)[0]; console.log('key is ' + pair[0]); console.log('value is ' + pair[1]); } f(v);
let foo = {foo: 'bar'}
let [key, value] = Object.entries(foo).flat();
console.log(key);
console.log(value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.