首页 > 解决方案 > 在javascript中获取对象值不起作用

问题描述

我想知道如何在 javacript 中获取对象的值。

如果来源与对象中的国家和付款类型匹配,则它应该得到速度和费用的值。例如,类型为“credit”的“SGD”应该返回速度和费用。

预期输出:

id: transfer  credit: 1 days 1% 
id: insta credit: 1 days 1.5%

function getValue(source, type, ob) {
    var list;
    ob.forEach((cn) => {
      list = cn.country_from.filter((c) => {
        return c.currency== source;
      });
    })
    return `${type} ${list[0].paymentIn[0].credit.number}`;
  }

//inputs
var result  = getValue(source,type,obj);
var source="SGD";
var type="credit";
var obj = [{
    "id": "transfer",
    "country_from": [{
        "currency": [
            "SGD",
            "USD"
        ],
        "paymentIn": [{
            "type": "credit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1"
            }
        }]
    }]
}, {
    "id": "insta",
    "country_from": [{
        "currency": [
            "SGD",
            "USD"
        ],
        "paymentIn": [{
            "type": "credit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1.5"
            }
        }]
    }]
}]

标签: javascriptobject

解决方案


首先应用过滤器来获取匹配的对象,country然后type您可以对过滤后的数组应用循环以获得所需的输出。

const inputCountry="SGD";
const inputType="credit";
const input =
 [
    {
        "id": "transfer",
        "country_from": [
            {
                "currency": [
                    "SGD",
                    "USD"
                ],
                "paymentIn": [
                    {
                        "type": "credit",
                        "speed": {
                            "unit": "days",
                            "number": "1"
                        },
                        "fee": {
                            "type": "%",
                            "number": "1"
                        }
                    }
                ]       
            }
        ]
    }
];

const filteredArr = input.filter(({country_from}) => {
    return country_from.filter(({currency, paymentIn}) => {
        const ispaymentIn = paymentIn.filter(({type}) => {
            return type.toLowerCase() === inputType.toLowerCase();
        })
        return currency.includes(inputCountry) && ispaymentIn;
    });
});

const output = filteredArr.map(({id, country_from}) => {
    let obj = {id};
    country_from.forEach(({paymentIn}) => {
        paymentIn.forEach(({type, speed, fee}) => {
            obj[type] = speed.number + speed.unit + ' ' + fee.number + fee.type;
        });
    });

    return obj;
});

console.log(output);


推荐阅读