无法获取嵌套数组对象中的对象值

时间:2019-03-29 04:06:11

标签: javascript arrays object

我想知道如何使用JavaScript在嵌套数组对象中获取对象值。如果sourcecountry与对象国家/地区匹配,则应返回付款服务。

我已经尝试过了:

funtion getValue(source, ob){
      var list  = obj.filter((cn)=>{
      return cn.country_from.filter((c)=>{
       return c.country == source
      })
   })
}
var result = getValue(sourcecountry, obj);


var sourcecountry = "SG";
var obj = [
    {
     "country_from": [
            {
                "country": "SG",
                "payment_service": [
                    {
                        "type": "bank transfer",
                         "speed": {
                          "unit": "days",
                         "number": "2"
                     },
                    }
                ]
            },
            {
                "country": "TH",
                "payment_service": [
                    {
                        "type": "credit",
                         "speed": {
                          "unit": "days",
                          "number": "1"
                      },
                    }
                ]
            }
        ]
    },
]

预期输出:

Speed: 2 Days

1 个答案:

答案 0 :(得分:0)

您可以使用下面的代码。您只需要1个.filter()而不是2个。您可以使外部一个为.forEach()

var sourcecountry = "SG";
var obj = [{
  "country_from": [{
      "country": "SG",
      "payment_service": [{
        "type": "bank transfer",
        "speed": "2 days"
      }]
    },
    {
      "country": "TH",
      "payment_service": [{
        "type": "credit",
        "speed": "1 day"
      }]
    }
  ]
}];
var result = getValue(sourcecountry, obj);
console.log(result);

function getValue(source, ob) {
  var list;
  ob.forEach((cn) => {
    list = cn.country_from.filter((c) => {
      return c.country == source;
    });
  })
  return `Speed: ${list[0].payment_service[0].speed}`;
}