我有一个带有动态键的对象数组
<div id="container">
<div class="something">this is the .something element; the class <code>else</code> makes it green</div>
</div>
我想将对象的这个数组展平为单个数组
var something = document.activeElement.querySelector('.something');
if (something) {
something.classList.add('else');
}
我尝试了以下操作:
response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];
答案 0 :(得分:7)
您可以只使用map和object.values
response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}]
const vals = response.map(o => Object.values(o)[0])
console.log(vals)
答案 1 :(得分:5)
您可以将.map()
与.concat()
一起使用:
let data = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];
let result = [].concat(...data.map(Object.values));
console.log(result);
答案 2 :(得分:1)
使用reduce和for..in
遍历对象
let response = [{
"1": 1
},
{
"2": 1
},
{
"3": 1
},
{
"4": 0
},
{
"5": 0
}
]
let k = response.reduce(function(acc, curr) {
for (let keys in curr) {
acc.push(curr[keys])
}
return acc;
}, [])
console.log(k)
答案 3 :(得分:1)
response = [{"1": 1},{"2": 1},{"3": 1},{"4": 0},{"5": 0}]
var newArray = []
for (element of response) {
Object.keys(element).map(key => {
newArray.push(element[key])
})
}
console.log(newArray)