[英]How to access the object from an Array in Type script
I have a list of objects in an array like this:我在这样的数组中有一个对象列表:
[
0: {name: "John", data: 0: [{age: 24}, {icon: "04d"}]},
1: {name: "Vicky",data: 0: [{age: 25}, {icon: "06d"}]},
2: {name: "John2",data: 0: [{age: 26}, {icon: "05d"}]},
4: {name: "John3",data: 0: [{age: 27}, {icon: "09d"}]},
]
I am trying to access the objects like this.我正在尝试访问这样的对象。
*ngFor="let weather_data of weather_data_info"
in my HTML but I can not access the elements like above, can anyone tell me what I am doing wrong, any other alternate method is also welcome在我的 HTML 但我无法访问上述元素,谁能告诉我我做错了什么,也欢迎任何其他替代方法
You need to convert your associative array to array since JS does not have such a type.您需要将关联数组转换为数组,因为 JS 没有这种类型。
And also your inner data is not valid too而且您的内部数据也无效
data: 0: [{age: 24}, {icon: "04d"}]
// This is not a valid structure
You need to remove keys from array:您需要从数组中删除键:
const weather_data_info = [
{name: "John", data: {0: [{age: 24}, {icon: "04d"}]}},
{name: "Vicky",data: {0: [{age: 25}, {icon: "06d"}]}},
{name: "John2",data: {0: [{age: 26}, {icon: "05d"}]}},
{name: "John3",data: {0: [{age: 27}, {icon: "09d"}]}},
];
Or if you want to use index
keys as ID
, you can convert it to object and use Object.values()
or Object.keys()
to iterate over it:或者,如果您想使用
index
键作为ID
,您可以将其转换为 object 并使用Object.values()
或Object.keys()
对其进行迭代:
const data = { 0: {name: "John", data: {0: [{age: 24}, {icon: "04d"}]}}, 1: {name: "Vicky",data: {0: [{age: 25}, {icon: "06d"}]}}, 2: {name: "John2",data: {0: [{age: 26}, {icon: "05d"}]}}, 4: {name: "John3",data: {0: [{age: 27}, {icon: "09d"}]}}, }; const weather_data_info = Object.keys(data).reduce((acc, key) => { acc.push({...data[key], id: key}); return acc; },[]); console.log(weather_data_info)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.