如何转化你的Object 变成 array of objects。 有多种方式去实现,但是作为前端工程师更希望使用更加好看的方式去实现
You may be asking why, the answer is actually quite simple. In programing we are not always in control of the format in which our data is delivered to us. With this in mind it becomes important to understand how to convert our data into our desired format.
The Example
Using Javascript features there is an easy one liner that can achieve this result using Object.values().
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
For example :
const peopleObj = {
jim: {
name: "jim",
age: 20
},
tim: {
name: "tim",
age: 22
}
}
const peopleArray = Object.values(peopleObj)
In my opinion if you are using babel go ahead and use this, if not I will show below how you can do this with a more widely supported feature, Object.keys().
Note: The following example uses the peopleObj from the above example.
const peopleArray = Object.keys(peopleObj).map(i => peopleObj[i])
This second method is quite well supported. Check out both Object Values and Object Keys MDN documentation to learn where you may have issues with support and for more info on these features.
If you want to use Object.entries for getting only values you could use like this:
const object1 = { foo: 'bar', baz: 42 };
console.log(Object.entries(object1)[1]);
// expected output: Array ["baz", 42]
* The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).