0

I have a months array that has 12 dynamically created objects for the next 12 months

 months = [
    {2020-02: Array(0)}
    {2020-03: Array(0)}
    {2020-04: Array(0)}
    {2020-05: Array(0)}
    {2020-06: Array(0)}
    {2020-07: Array(0)}
    {2020-08: Array(0)}
    {2020-09: Array(0)}
    {2020-10: Array(0)}
    {2020-11: Array(0)}
    {2020-12: Array(0)}
    {2021-01: Array(0)}
    ];

I want to insert an object into the object's array based on a dynamic key that is based on another array (source data).

I loop through the source data and each object in the source data's array has a key of media_date and value of 2020-02;

I then create an object to insert into the months array

var person = new Object();
person.title = 'job title';
person.name = 'cool name';

I want to insert the person object into the months array into the object with the key of 2020-02

I tried something like:

$.each(source,function(i,data){
    var person = new Object();
    person.title = data.job_title;
    person.name = data.name;
  var key = data.monthyear (2020-02)
  months.[key].push(person);
});

But I get

TypeError: Cannot read property 'push' of undefined at...

Thanks for any help you can give!

4
  • 1
    in js has this syntax months.[key]? Commented Feb 27, 2020 at 16:53
  • 2
    months[key].push(person);, you don't need the '.' (dot) between months and your key Commented Feb 27, 2020 at 16:54
  • months[key] = person? Commented Feb 27, 2020 at 16:55
  • 1
    syntax error months.[key] and keys with hypen is not a good idea change to "2021-01" or 2020101 Commented Feb 27, 2020 at 16:55

1 Answer 1

1

Assuming that the months array is:

months = [
{'2020-02': Array(0)},
{'2020-03': Array(0)},
{'2020-04': Array(0)},
{'2020-05': Array(0)},
{'2020-06': Array(0)},
{'2020-07': Array(0)},
{'2020-08': Array(0)},
{'2020-09': Array(0)},
{'2020-10': Array(0)},
{'2020-11': Array(0)},
{'2020-12': Array(0)},
{'2021-01': Array(0)}
];

findMonth = '2020-02';

use one of the following to find the position of the wanted object:

  • index = months.findIndex(x => Boolean(x[findMonth]))
  • index = months.findIndex(x => Object.keys(x)[0] === findMonth)

then use the following to push at the value of the key months[index][findMonth].push(person)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.