【问题标题】:Adding a Json Object after a particular Object in array in javascript在javascript中的数组中的特定对象之后添加一个Json对象
【发布时间】:2021-07-20 05:41:05
【问题描述】:

我有一个对象数组,看起来像

arr = [
    {"className":"section", "name":"input"},
    {"className":"col", "name":"dropdown"},
    {"className":"section", "name":"table"}
] 

现在我想在每个具有 "className":"section" 的对象之后推送一个对象 {"fieldName":"new"}

所以我的最终输出应该是这样的

arr = [
    {"className":"section", "name":"input"},
    {"fieldName":"new"},
    {"className":"col","name":"dropdown"},
    {"className":"section", "name":"table"},
    {"fieldName":"new"}]

如何在 Javascript 中实现这一点?

【问题讨论】:

标签: javascript arrays json object


【解决方案1】:

使用Array.reduce。

let arr = [{"className":"section", "name":"input"},{"className":"col", "name":"dropdown"},{"className":"section", "name":"table"}];

arr = arr.reduce((acc, item) => {
    acc.push(item);
    if (item.className === "section") {
        acc.push({ fieldName: "new" });
    }
    return acc;
}, []);

console.log(arr);

【讨论】:

  • @SriramCh 没问题 - 愿意接受答案吗?
【解决方案2】:

试试这个...

arr.forEach(obj => {
 if (obj.className === 'section') {
  const index = arr.indexOf(obj)
  arr.splice(index, 0, 
  {"fieldName":"new"} )
 }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2018-10-04
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多