Angular 2如何从对象数组获取键值?

时间:2018-12-12 17:55:34

标签: javascript arrays typescript

我有object array

enter image description here

{"-LTYJbW1B3mhrdc6C64N":{"done":0,"name":"Job2","pt":5},"-LTYJcSOUh07SQcixP4x":{"done":0,"name":"Job3","pt":5}}

看来,有两个带有随机键(--LTYJbW1B3mhrdc6C64N)的对象,我想获得这些键,我该怎么做?

HTML:

<div class="task-block" *ngFor="let task of objectValues(team.tasks)">
 <p >{{task.name}}</p>
 <button mat-raised-button (click)="updateTask(task)">Done!</button>
  <i class="material-icons deletetask">close </i></div>

TS:

objectValues(obj) { 
  if(obj){
    console.log(JSON.stringify(obj))
    return Object.values(obj || {});
  }

  }



updateTask(task){
      console.log(task.key); //here I want to get task.key
    }

5 个答案:

答案 0 :(得分:1)

html

<div class="task-block" *ngFor="let task of tasks | keyvalue">
  <div (click)="itemClick(task.key)>{{task | json}}</div>
</div>

ts

export class AppComponent  {
  task = {
    "-LTYJbW1B3mhrdc6C64N": {"done":0,"name":"Job2","pt":5},
    "-LTYJcSOUh07SQcixP4x":{"done":0,"name":"Job3","pt":5}
  };

  itemClick(key) {
     console.log(key);
  }
}

答案 1 :(得分:0)

这些对象也是在数组中还是它们自己?

如果它们在数组中,则可以使用它来遍历对象键,从而在其中给出“名称”和子值

Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});

在您的情况下,您只需要第一级名称。只是object.keys应该可以解决问题。

console.log(Object.keys(obj));

来源: Javascript object loop

答案 2 :(得分:0)

您可以使用Object.keys,它将为您提供对象键的数组。

我希望这能解决问题。

let obj = {"-LTYJbW1B3mhrdc6C64N":{"done":0,"name":"Job2","pt":5},"-LTYJcSOUh07SQcixP4x":{"done":0,"name":"Job3","pt":5}}

let keysOfObj = Object.keys(obj)

console.log("keys of the obj =>", keysOfObj)

答案 3 :(得分:0)

var keys = Object.keys(YourObject)
console.log(keys)
// ["key1", "keys2",...]


updateTask(task){
   var keys = Object.keys(task)
   console.log(keys[0]);
   return keys[0]
}

MDN Object.keys()

答案 4 :(得分:0)

Object.keys()是您所需要的。

let obj = {
"-LTYJbW1B3mhrdc6C64N":{"done":0,"name":"Job2","pt":5},
"-LTYJcSOUh07SQcixP4x":{"done":0,"name":"Job3","pt":5}
}

let op = Object.keys(obj);
console.log(op);