Use Object.fromEntries to convert an array into an object
The Object.fromEntries() method converts a list of key-value pairs into an object.
grammar:
-
Object.fromEntries(iterable)
iterable
: Similar to Array, Map or other iterable objects that implement the iterable protocol.
return a new object
let keyArray = [
['name','Yimning'],
['age','18']
]
console.log(Object.fromEntries(keyArray))
// {name:'Yimning',age:'18'}
- Object.entries()
Object.entries(obj)
method returns an array of key-value pairs of the given object's own enumerable properties, in the same order as would be for...in
returned when looping through the object (with the difference that for-in
the loop also enumerates properties in the prototype chain).
let keyObj = {
name:'Yimning',
age:'18'
}
console.log(Object.entries(keyObj))
// [['name','Yimning'],['age','18']]
Among them, Object.entries() and Object.fromEntries() are reciprocal operations
Use Object.fromEntries to convert the Map into an object
object.fromEntries() can also convert the data of the Map data type into an object
let map = new Map([['name','Yimning'],['age','18']])
console.log(map)
// {"name" => "Yimning", "age" => "18"}
console.log(Object.fromEntries(map))
// {name:'Yimning',age:'18'}
Mixed use of Object.entries and Object.fromEntries - object to object conversion
let age = {p1:18,p2:19,p3:20}
const result = Object.fromEntries(Object.entries(age).filter(([key,value])=> value > 19))
console.log(result)
// {p3: 20}
If not make Object.fromEntries convert the array into an object, how should it be achieved?
let arr = [
['name','Yimning'],
['age',18]
]
function toObject(arr){
return Array.from(arr).reduce(
(acc,[key,value]) => Object.assign(acc,{[key]:value}), {}
)
}