繁体   English   中英

append 到数组中作为 object 中的值

[英]append to an array as a value in an object

我正在返回 object 文件夹的结构以及其中包含的 json 文件的内容。 这就是它的样子。

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

当一个文件夹有两个以上的文件时,我会遇到问题,因为我找不到将 append 连接到 monday 或 DailyTask 数组的方法

我尝试进行 concat 或 push 但起初它们不起作用,因为 object 属性未定义所以我做了第一个分配将通过方括号完成,随后的分配将通过 push 或 unshift 完成,即 x 是 json 文件

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

给我这个

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

它显示为 [[Object]],我如何使 object 的实际内容显示。

从您呈现的逻辑x等于[ {...} ] 这就是为什么它适用于

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

但另一方面失败了: title: [ [{...}], {...} ]

尝试这个:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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