0

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

2
  • 2
    Your array structure is not valid. There's no associative array in JS. So you can not have keys in the array like this. Commented Jul 13, 2020 at 5:36
  • How to covert it...? Commented Jul 13, 2020 at 5:40

1 Answer 1

1

You need to convert your associative array to array since JS does not have such a type.

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:

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.