我有一个对象数组,并尝试将这些对象中的值取入并基于相同的属性值将它们推入数组中。例如。
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
<div id="app" class="container">
<span class="text-muted pr-2" >
{{ago}}
</span>
</div>
我有这个对象数组,现在我想遍历对象并创建具有所有名称值和年龄值的数组。数组还需要与值同名。结果就是这样。
array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
我该怎么做?
答案 0 :(得分:1)
map
就像这样遍历数组:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
const name = array.map(e => e.name);
const age = array.map(e => e.age);
console.log(name);
console.log(age);
如果数组具有动态对象,则可以执行以下操作:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
];
for (var key in array[0]) {
window[key] = array.map(e => e[key]);
}
console.log(name);
console.log(age);