简体   繁体   中英

append to an array as a value in an object

i am returning a structure of an object of folders and the contents of the json files contained in them. this is how it's looks like.

{
  DailyTask: [ { title: 'Chores', body: 'Wash the roof and sweep the bed' } ],
  monday: [{ title: 'madrid', body: 'Wash the roof and sweep the bed' }  ],
}

i have a problem when a folder has more than two files, because i can't find a way to append to the array of either monday or DailyTask

i tried doing concat or push but they wouldn't work at first because the object property is undefined so i did the first assignment would be done via square brackets and subsequent ones will be done via push or unshift ie x is the json file

if (sum[key] == undefined) {
            sum[key] = x;
        } else {
            sum[key].unshift(x);
        }

gives me this

{
  DailyTask: [ { title: 'Chores', body: 'Wash the roof and sweep the bed' } ],
  monday: [
    [ [Object] ],
    { title: 'madrid', body: 'Wash the roof and sweep the bed' }
  ]
}

it shows as [[Object]], how do i make the actual contents of the object show.

From the logic you are presenting x equals [ {...} ] . that is why it works for

sum[key] = x;
// outputs:
// title: [ { ... } ]

But fails on the other: title: [ [{...}], {...} ]

try this:

if (sum[key] == undefined) {
  sum[key] = [x[0]] ; // or simply leave it x;
} else {
  sum[key].unshift(x[0]);
}
if(sum[key]==undefined) sum[key]=[x];
else sum[key].push(x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM