Object.fromEntries()
方法从键值对列表创建对象。
示例
const arr = [
["0", "a"],
["1", "b"],
["2", "c"],
];
// convert the above array into an object
const newObj = Object.fromEntries(arr);
console.log(newObj);
// Output: { '0': 'a', '1': 'b', '2': 'c' }
fromEntries() 语法
fromEntries()
方法的语法是:
Object.fromEntries(iterable)
在这里,fromEntries()
是一个静态方法。因此,我们需要使用类名 Object
来访问该方法。
fromEntries() 参数
fromEntries()
方法接收
fromEntries() 返回值
fromEntries()
方法返回
- 一个新对象,其属性由可迭代对象的条目给出。
注意: Object.fromEntries()
执行与 Object.entries()
相反的功能。
示例:JavaScript Object.fromEntries()
const entries = [ ["firstName", "John"],
["lastName", "Doe"]
];
// convert the above array into an object
const obj = Object.fromEntries(entries);
console.log(obj);
const arr = [
["0", "x"],
["1", "y"],
["2", "z"],
];
// convert the above array into object
const newObj = Object.fromEntries(arr);
console.log(newObj);
输出
{ firstName: 'John', lastName: 'Doe' } { '0': 'x', '1': 'y', '2': 'z' }
在上面的示例中,我们首先创建了 entries 数组,它包含两个键值对:["firstName", "John"]
和 ["lastName", "Doe"]
。
然后,我们使用 Object.fromEntries()
方法将 entries 数组转换为一个对象,该对象具有数组中指定的键值对。
const obj = Object.fromEntries(entries);
输出显示数组已成功转换为相应的对象。
然后,我们使用 arr 数组重复了相同的过程。
另请阅读