简体   繁体   English

如何在Vue.js中获取对象数组中的键

[英]How to get keys in Object array in Vue.js

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? 我如何达到目标?

You can use Object.keys with Object.assign and spread the data into one object to get all the keys: 您可以将Object.keysObject.assign一起使用,并将data分散到一个对象中以获取所有键:

 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. 这样做的主要原因是由于您正在处理数组,而Object.keys期望对象可以工作。

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])); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM