【问题标题】:append to an array as a value in an object作为对象中的值附加到数组
【发布时间】:2020-08-09 22:38:28
【问题描述】:

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

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

当一个文件夹有两个以上的文件时,我会遇到问题,因为我找不到追加到星期一或 DailyTask 数组的方法

我尝试过 concat 或 push 但起初它们不起作用,因为对象属性未定义所以我做了第一个分配将通过方括号完成,随后的分配将通过 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]],如何让对象的实际内容显示出来。

【问题讨论】:

  • Ciao,所以您想创建一个包含对象{ title: 'Chores', body: 'Wash the roof and sweep the bed' }{ title: 'madrid', body: 'Wash the roof and sweep the bed' } 的唯一数组,对吗?
  • 向我们展示之前和之后的结果。
  • @Sascha 第一个代码块和最后一个代码块是结果
  • @GiovanniEsposito 我想添加更多的格式 { title: 'XXXXX', body: 'Do something xxxxxxx' }
  • yourObject.monday.push({title:"foo"});应该管用。提供您的问题的 jsfiddle。

标签: javascript arrays json object key-value


【解决方案1】:

根据您提出的逻辑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]);
}

【讨论】:

  • 你误会了我,我正在推送格式为 { 标题:'XXX',正文:'bla bla bla bla'} 的对象,而不是标题:[ [{...}],{.. .}]
  • 但这正是您得到的输出。 [[ [Object] ],{ title: 'madrid', body: 'Wash the roof and sweep the bed' }]。我提供的解决方案仍然不起作用?
【解决方案2】:
if(sum[key]==undefined) sum[key]=[x];
else sum[key].push(x);

【讨论】:

  • 这个不行,后续推送的对象显示为[[Object]]
  • 对我来说没有意义。 x 是什么? console.log 看看是不是这样:{"title":"something", "body":"something else"}.
猜你喜欢
  • 2013-08-20
  • 2020-08-15
  • 1970-01-01
  • 2022-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多