admin管理员组文章数量:1355703
I have an object array created and it's like this:
for(var i =0; i < this.test.length; i ++){
var header = this.test[i].hdr;
var insertData = [];
switch(header){
case 'date':
insertData = {date: "date"};
break;
case 'name':
insertData = {name: "name"};
break;
case 'age':
insertData = {age: "age"};
break;
case 'add':
insertData = {add: "add"};
break;
}
this.hdrtxt.push(insertData);
}
Now, when I try to get the keys of the object, I used this:
Object.keys(this.hdrtxt);
The result is:
(4) ["0", "1", "2", "3"]
But the output I want is this:
(4) ["date", "name", "age", "add"]
I'm sorry I'm just new to this. How can I attain my goal?
I have an object array created and it's like this:
for(var i =0; i < this.test.length; i ++){
var header = this.test[i].hdr;
var insertData = [];
switch(header){
case 'date':
insertData = {date: "date"};
break;
case 'name':
insertData = {name: "name"};
break;
case 'age':
insertData = {age: "age"};
break;
case 'add':
insertData = {add: "add"};
break;
}
this.hdrtxt.push(insertData);
}
Now, when I try to get the keys of the object, I used this:
Object.keys(this.hdrtxt);
The result is:
(4) ["0", "1", "2", "3"]
But the output I want is this:
(4) ["date", "name", "age", "add"]
I'm sorry I'm just new to this. How can I attain my goal?
Share Improve this question edited Dec 7, 2018 at 1:58 tony19 139k23 gold badges277 silver badges347 bronze badges asked Dec 7, 2018 at 1:42 Eem JeeEem Jee 1,3197 gold badges34 silver badges67 bronze badges 2-
How are you calling
Object.keys(this.hdr)
?.hdr
looks like a property of each object in thethis.test
array. – achacttn Commented Dec 7, 2018 at 1:47 - @achacttn Opppss updated. Variable name typo :) – Eem Jee Commented Dec 7, 2018 at 1:54
2 Answers
Reset to default 5You can use Object.keys
with Object.assign
and spread the data
into one object to get all the keys:
const data = [{ date: "date" }, { name: "name" }, { age: "age" }, { add: "add" }]
const result = Object.keys(Object.assign({}, ...data))
console.log(result)
The main reason for this is due to the fact that you are dealing with an array and Object.keys
expects an object to work.
First off that could be done much easier in a reduce
const test = [{hdr: "date"}, {hdr: "name"}, {hdr: "age"}, {hdr: "add"}];
const results = test.reduce((result, item) => [...result, { [item.hdr]: item.hdr }], []);
// This logs, ["0", "1", "2", "3"] because it is an array and the keys are integers.
console.log(Object.keys(results));
// If you want the object keys for each item in the array try mapping each item in the array to it's first key in the keys for that item
console.log(results.map(item => Object.keys(item)[0]));
本文标签: javascriptHow to get keys in Object array in VuejsStack Overflow
版权声明:本文标题:javascript - How to get keys in Object array in Vue.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743940996a2565559.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论