我有一些对象数组,其中每个对象都有一个对象,如下所示。
[{
"-KzbaPS3vuZTG2LbuB3j": {
"age": "24",
"branchname": "columbia",
"city": "hyd",
"date": 1511418820987,
"gender": "M",
"id": "rcjcx8",
"mobile": "9898989898",
"name": "Patient1",
"op": 100
}
}, {
"-KzTh7RTtTWviL4HkHv0": {
"age": "21",
"branchname": "kims",
"city": "vizag",
"date": 1511334303070,
"gender": "F",
"id": "45krxb",
"mobile": "9898989898",
"name": "aruna",
"op": 100
},
"-KzTiCIheMPJIpJhPXQJ": {
"age": "22",
"branchname": "kims",
"city": "hyderabad",
"date": 1511420593865,
"gender": "F",
"id": "c7iqws",
"mobile": "9878787878",
"name": "vineesha",
"op": 100
},
"-KzTnzLnRsdFWg-m5b9U": {
"age": "26",
"branchname": "kims",
"city": "bheemavaram",
"date": 1511420593865,
"gender": "F",
"id": "ujtgz",
"mobile": "9876787898",
"name": "Madhavi",
"op": 100
}
}]
对象未知,那么如何将对象的所有对象都放入数组?
答案 0 :(得分:1)
您可以使用
array.forEach(obj => {
let key = Object.keys(obj)[0];
let yourValue = obj[key];
// yourValue = { "age": "21", "id": "rcjcx8" ...} in your case for the first item
});
答案 1 :(得分:0)
如果您对Lodash没事,您可以执行以下操作:
// assuming the above data is in variable "data"
let structuredData = _.flatten(data).reduce((a,c) => _.assign(c), {});
答案 2 :(得分:0)
迭代并获取密钥并使用密钥获取值。 Working version
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 5';
jsonDataKeys : any=[];
jsonData : any =[{
"-KzbaPS3vuZTG2LbuB3j": {
"age": "24",
"branchname": "columbia",
"city": "hyd",
"date": 1511418820987,
"gender": "M",
"id": "rcjcx8",
"mobile": "9898989898",
"name": "Patient1",
"op": 100
}
}, {
"-KzTh7RTtTWviL4HkHv0": {
"age": "21",
"branchname": "kims",
"city": "vizag",
"date": 1511334303070,
"gender": "F",
"id": "45krxb",
"mobile": "9898989898",
"name": "aruna",
"op": 100
},
"-KzTiCIheMPJIpJhPXQJ": {
"age": "22",
"branchname": "kims",
"city": "hyderabad",
"date": 1511420593865,
"gender": "F",
"id": "c7iqws",
"mobile": "9878787878",
"name": "vineesha",
"op": 100
},
"-KzTnzLnRsdFWg-m5b9U": {
"age": "26",
"branchname": "kims",
"city": "bheemavaram",
"date": 1511420593865,
"gender": "F",
"id": "ujtgz",
"mobile": "9876787898",
"name": "Madhavi",
"op": 100
}
}];
constructor(){
for(let arr of this.jsonData){
Object.keys(arr) && Object.keys(arr).map((key)=>{
console.log("push")
this.jsonDataKeys.push(key);
});
}
}
}
HTML文件
{{jsonDataKeys}}
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<!--<div>{{jsonData | json}}</div>-->
<div *ngFor="let arr of jsonData">
<div *ngFor="let item of jsonDataKeys">
item : {{item}}
{{arr[item] | json}}
<br>
<br>
</div>
</div>