【问题标题】:How to get the object value based on a certain condition in JavaScript?JavaScript中如何根据特定条件获取对象值?
【发布时间】:2021-12-29 06:54:50
【问题描述】:

我在玩 JS 对象。我遇到了一个对我来说具有挑战性的情况:

基本上我有一个 JS 对象:

let cinfo = {
   "costing_T063623477Z":{
      "service":[
         {
            "objid":"T063637283Z",
            "serviceid":"SRV2100003",
            "servicename":"FABRICATION OF SPRINKLER & HOSE",
            "estimatedprice":"10000.00",
            "description":"sdfg",
            "laborcost":"500.00"
         }
      ],
      "othercharges":[
         {
            "objid":"T063911531Z",
            "description":"Other Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063906963Z",
            "description":"Sales Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063730836Z",
            "description":"Delivery Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063730836Z",
            "description":"Delivery Expenses",
            "amount":"345.00",
            "remarks":"345"
         }
      ]
   }
}

我有东西可以获取特定对象的值:

Object.keys(cinfo).forEach(function(ckey) {
     cinfo[ckey].service.forEach(function(skey){
         console.log(skey.laborcost);
     })
})

根据上面的对象,控制台输出为:500.00

但是,当涉及到othercharges 对象时,我想要一些有条件的东西。 我只需要根据描述获取金额:

类似这样的:

Object.keys(cinfo).forEach(function(ckey) {
     cinfo[ckey].othercharges.forEach(function(skey){
          console.log(skey.amount) //-> where "description" = "Other Expenses";
          console.log(skey.amount) //-> where "description" = "Sales Expenses";
          console.log(skey.amount) //-> where "description" = "Delivery Expenses";
     })
}

如何使它成为可能?谢谢。

【问题讨论】:

标签: javascript arrays


【解决方案1】:

这样的?

let cinfo = {
   "costing_T063623477Z":{
      "service":[
         {
            "objid":"T063637283Z",
            "serviceid":"SRV2100003",
            "servicename":"FABRICATION OF SPRINKLER & HOSE",
            "estimatedprice":"10000.00",
            "description":"sdfg",
            "laborcost":"500.00"
         }
      ],
      "othercharges":[
         {
            "objid":"T063911531Z",
            "description":"Other Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063906963Z",
            "description":"Sales Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063730836Z",
            "description":"Delivery Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063730836Z",
            "description":"Delivery Expenses",
            "amount":"100.00",
            "remarks":"345"
         }
      ]
   }
}

const getServiceCharge = (info) => {
  const key = Object.keys(info)[0]; // Get first key in object
  return info[key].service[0].laborcost;
}

const getOtherCharge = (info, desc) => {
  const key = Object.keys(info)[0]; // Get first key in object
  const otherCharges = info[key].othercharges;
  
  const sumAmount = otherCharges
    .filter(item => item.description === desc) // Get only items we are looking for
    .reduce((sum, item) => sum + Number(item.amount), 0); // Sum amount 

  return sumAmount;    
}

console.log(`Service Labor charge: ${getServiceCharge(cinfo)}`);
console.log(`Service Other Expenses charge: ${getOtherCharge(cinfo, "Other Expenses")}`);
console.log(`Service Sales Expenses charge: ${getOtherCharge(cinfo, "Sales Expenses")}`);
console.log(`Service Delivery Expenses charge: ${getOtherCharge(cinfo, "Delivery Expenses")}`);

【讨论】:

  • 如果有多个“运费”怎么办?我更新了我的问题
  • 你想要答案,所有“快递”的总价值?
  • 我更新了我的答案:)
  • 是的,它应该添加所有具有相同描述的。
【解决方案2】:
Object.keys(cinfo).forEach(function(ckey) {
     // Get only 1 other charges
     // Return object
     const deliveryExpenses = cinfo[key].othercharges.find(item => item.description == "Delivery Expenses")
     // Get all other charges base on the comparison
     // Returns array
     const deliveryExpenses = cinfo[key].othercharges.filter(item => item.description == "Delivery Expenses")

}

这里是使用 find 的文档。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

【讨论】:

  • 哇。这很好用!
  • 如果有多个“运费”怎么办?
  • 它只会让第一个出现,如果你想得到所有那些Delivery Expenses你必须使用过滤器来代替
  • 我使用过滤器,它返回“未定义”
  • 这很奇怪,你能分享你的代码吗?
【解决方案3】:

let cinfo = {
  costing_T063623477Z: {
    service: [
      {
        objid: "T063637283Z",
        serviceid: "SRV2100003",
        servicename: "FABRICATION OF SPRINKLER & HOSE",
        estimatedprice: "10000.00",
        description: "sdfg",
        laborcost: "500.00"
      }
    ],
    othercharges: [
      {
        objid: "T063911531Z",
        description: "Other Expenses",
        amount: "345.00",
        remarks: "345"
      },
      {
        objid: "T063906963Z",
        description: "Sales Expenses",
        amount: "345.00",
        remarks: "345"
      },
      {
        objid: "T063730836Z",
        description: "Delivery Expenses",
        amount: "345.00",
        remarks: "345"
      }
    ]
  }
};

function getCharge(serviceCharge = null, otherCharges = null) {
  if (serviceCharge) {
    return cinfo.costing_T063623477Z.service[0].laborcost;
  }
  return cinfo.costing_T063623477Z.othercharges.filter(
    (t) => t.description === otherCharges
  ).map(t=>t.amount);
}

console.log(getCharge(true));
console.log(getCharge(null, "Other Expenses"));
console.log(getCharge(null, "Sales Expenses"));
console.log(getCharge(null, "Delivery Expenses"));

让我们以更聪明的方式来做。我希望它会起作用。

【讨论】:

  • 如果有多个“运费”怎么办?我更新了我的问题
  • 亲爱的@jreloz 我只是编辑答案。如果有多个对象,则必须使用过滤方法。
【解决方案4】:

这是一个答案,只使用一个循环(通过.reduce),只需在正确的位置分配一些变量即可设置所有内容。

它适用于多个services 或多个descriptions 共享相同的值。

let cinfo = {
   "costing_T063623477Z":{
      "service":[
         {
            "objid":"T063637283Z",
            "serviceid":"SRV2100003",
            "servicename":"FABRICATION OF SPRINKLER & HOSE",
            "estimatedprice":"10000.00",
            "description":"sdfg",
            "laborcost":"500.00"
         }
      ],
      "othercharges":[
         {
            "objid":"T063911531Z",
            "description":"Other Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063906963Z",
            "description":"Sales Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063730836Z",
            "description":"Delivery Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063730836Z",
            "description":"Delivery Expenses",
            "amount":"100.00",
            "remarks":"345"
         }
      ]
   }
}

function getCost(obj, othercharges) {
  let key = Object.keys(obj)[0],
      subKey =   (othercharges) ? 'othercharges' : 'service',
      property = (othercharges) ? 'amount'       : 'laborcost',
      childObj = obj[key][subKey];
  
  return childObj.reduce((totalSum, item) => {
    let itemSum = 0;
    
    if (!othercharges || item.description == othercharges) {
      itemSum = item[property];
    }

    return totalSum + Number(itemSum);
  }, 0);
}

console.log( getCost(cinfo) ); // returns 'laborcost'
console.log( getCost(cinfo, 'Delivery Expenses') );

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多