mia
mia

Reputation: 255

How to fetch the value in object array in javascript

I would like to know how to get/fetch the object in nested array using 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);

Upvotes: 4

Views: 7337

Answers (4)

Anil Kumar Moharana
Anil Kumar Moharana

Reputation: 374

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

Upvotes: 0

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

To get the array of objects that includes the selected currency in the variable value you can use Array.prototype.filter() combined with 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);

Note that instead of a function getData using variables out of function scope it is better pass the parameters you need in the function getData(obj, value)

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36564

e.ccy is an array. Comparing it with any other variable will never return true unless both have same reference. To check if the element is present in array using 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);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074148

It's hard to tell from your question, but if you want the first matching entry in the array, you're looking for the find method, using includes on ccy in the search:

function getData(){
    return obj.find(e => e.ccy.includes(value));
}

Live Example:

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);

Upvotes: 0

Related Questions