2018-09-26
Lightman Wang
如何转化你的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.
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).
IT Support 训练营01期
2025/11/10 06:13 (Sydney)
CCNA考证班01期
2025/09/06 08:37 (Sydney)
商业数据分析实战班第17期
2025/03/15 06:13 (Sydney)
地址
Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)Level 2, 171 La Trobe St, Melbourne VIC 3000四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号Business Hub, 155 Waymouth St, Adelaide SA 5000Disclaimer
JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.
匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议
© 2017-2024 JR Academy Pty Ltd. All rights reserved.
ABN 26621887572