javascript - 在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"
}
}]
}]
}]
解决方案
首先应用过滤器来获取匹配的对象,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);
推荐阅读
- angular - Angular Service Worker 间歇性地为旧版本的应用程序提供服务
- c# - 解析正则表达式查询
- node.js - NodeJS 应用程序如何以 sudo 身份重新启动?
- javascript - 访问 _ from origin _ 被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有 HTTP ok 状态
- awk - 如何提取两个字符之间的字符串?
- postgresql - 带有 null 参数的 Postgres SQL 函数为简单的 case/when/else 生成 null
- opencv - 如何优化我的代码以获得更好的执行时间
- zstd - 告诉 zstdcat 只解压缩文件的前 N 个字节
- javascript - JavaScript:创建一个函数,创建并返回一个函数;函数未定义错误
- git - 如何回到git中的master分支?