我想知道如何使用javascript获取/获取嵌套数组中的对象。
var value = "SGD"
var obj=[{
country: singapore,
ccy: ["EUR","SGD"]
amount: "1000"
},{
country: thailand,
ccy: ["THB"]
amount: "1000"
}]
function getData(){
return obj.filter((e)=>{
return e.ccy == value; // fetch array object if it matches the value
}
}
var result = getData();
console.log(result);
答案 0 :(得分:1)
要获取在变量value
中包含所选货币的对象数组,可以将Array.prototype.filter()与Array.prototype.includes()结合使用:
const value = 'SGD';
const obj = [{country: 'singapore',ccy: ['EUR', 'SGD'],amount: '1000'}, {country: 'thailand',ccy: ['THB'],amount: '1000'}];
const getData = (arr, value) => arr.filter(o => o.ccy.includes(value));
const result = getData(obj, value);
console.log(result);
请注意,最好不要在函数getData
中传递变量,而最好在函数getData(obj, value)
中传递所需的参数,而不是使用函数{{1}}
答案 1 :(得分:0)
很难从您的问题中看出来,但是,如果要在数组中第一个匹配的条目,则可以使用find
来寻找includes
方法ccy
在搜索中:
function getData(){
return obj.find(e => e.ccy.includes(value));
}
实时示例:
var value = "SGD";
var obj= [{
country: "singapore",
ccy: ["EUR","SGD"],
amount: "1000"
},{
country: "thailand",
ccy: ["THB"],
amount: "1000"
}];
function getData() {
return obj.find(e => e.ccy.includes(value));
}
var result = getData();
console.log(result);
答案 2 :(得分:0)
e.ccy
是一个数组。与任何其他变量进行比较将永远不会返回true
,除非两者都有相同的引用。使用Array.prototype.includes()
var value = "SGD";
var obj=[{
country: 'singapore',
ccy: ["EUR","SGD"],
amount: "1000"
},{
country: 'thailand',
ccy: ["THB"],
amount: "1000"
}]
function getData(){
return obj.filter((e)=>{
return e.ccy.includes(value)
})
}
var result = getData();
console.log(result);
答案 3 :(得分:0)
var obj=[{
country: 'singapore',
ccy: ["EUR","SGD"],
amount: "1000"
},{
country: 'thailand',
ccy: ["THB"],
amount: "1000"
}]
function getData(val) {
var result = obj.find(function(o) {
return o.ccy.indexOf(val) > -1;
});
return result;
}
console.log(getData('SGD'));