如何在JavaScript中获取对象数组中的值

时间:2019-05-15 08:19:38

标签: javascript html arrays object

我想知道如何使用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);

4 个答案:

答案 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'));