繁体   English   中英

如何使用javascript嵌套对象数组中的另一个属性值设置特定属性值?

[英]How to set specific property value with another property value in a javascript nested object array?

 var arr = {
    "data": [
    {
        id    : "a1",
        guid  : "sdfsfd",
        value : "abc",
        "status": "active"
      },
      {
        id    : "a2",
        guid  : "deaf",
        value : "def2",
       details : {
         "status": "inactive",
          "body": done
                  }
        "stat": "inactive"
      },
      {
        id    : "a2",
        guid  : "blind",
        value : "def4",
        details : {
           "status": "inactive",
           "body": donenot
                  }
        "stat": "inactive"
      },
    ]
      
    }
    
    console.log(arr.data.filter(item => item.stat === "inactive"))

输出

 [{
  details: {
    body: "done",
    status: "inactive"
  },
  guid: "deaf",
  id: "a2",
  stat: "inactive",
  value: "def2"
}, {
  details: {
    body: "done",
    status: "inactive"
  },
  guid: "blind",
  id: "a3",
  stat: "inactive",
  value: "def4"
}]

如果我想设置怎么办

  1. 每个此类非活动状态的值(在这 2 个输出中)--> value属性与guid属性相同...?
  2. 每个此类非活动状态的值(在这 2 个输出中)-->详细信息正文相同的状态

为了

  1. 你可以这样做: arr.data = arr.data.filter(item => item.stat === "inactive").map(e => ({...e, value : e.guid}))

输出

{
  data: [{
  details: {
    body: "done",
    status: "inactive"
  },
  guid: "deaf",
  id: "a2",
  stat: "inactive",
  value: "deaf"
}, {
  details: {
    body: "done",
    status: "inactive"
  },
  guid: "blind", --> same as value
  id: "a3",
  stat: "inactive",
  value: "blind"
}]
}

为了

  1. 你可以这样做: arr.data = arr.data.filter(item => item.stat === "inactive").map(e => ({...e, details : {...e.details, status: e.details.body}}))

输出

{
  data: [{
  details: {
    body: "done",
    status: "done"
  },
  guid: "deaf",
  id: "a2",
  stat: "inactive",
  value: "def2"
}, {
  details: {
    body: "done",
    status: "done"
  },
  guid: "blind",
  id: "a3",
  stat: "inactive",
  value: "def4"
}]
}

暂无
暂无

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

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