Search code examples
javascriptarraysreactjsapijavascript-objects

Adding an array property to an existing array of objects


I am trying to add the days of the week into an existing array of objects Current Array

I have filtered my array to only provide me exactly 7 results. For each of the objects i get back i want to add a property for Day: "Sunday" <- this is an example day, i need all 7, feels like a for each look might be needed but i just cant figure it.

let weekdays = { day: 'Monday', day: 'Tuesday', day: 'Wednesday', day: 'Thursday', day: 'Friday', day: 'Saturday', day: 'Sunday' }
    const weekdayRecipes = props.recipes.map(recipe => ({ ...recipe, ...weekdays }))

The above is what i tried but it doesnt work


Solution

  • You can't have multiple properties with the same key in an object. Every key needs to be unique. Take a look at this example:

    let weekdays = { day: 'Monday', day: 'Tuesday', day: 'Wednesday' }; // ...
    console.log(weekdays.day);
    

    What would you expect this snippet to log? Monday? Wednesday? It would actually log Wednesday, but that's because the other two properties (Monday and Tuesday) were overwritten by the last property. You need an array.

    You can either use a simple array consisting of only the weekdays, or if you need a little more than that, use an array of objects:

    // Simple array
    let weekdays = ['Monday', 'Tuesday', 'Wednesday'];
    console.log(weekdays[0]); // Monday
    
    // ... or an array of objects
    let weekdays = [{ weekday: 'Monday' }, { weekday: 'Tuesday' }, weekday: 'Wednesday' }];
    console.log(weekdays[0].weekday) // Monday
    

    If I understood you correctly, you now want to add one weekday per result into the props.recipes array. Using the first solution (simple array), this could look something like this:

    let weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    let weekdayRecipes = props.recipes.map((recipe, index) => ({ ...recipe, weekday: weekdays[index] }));