Samson Kemba
Samson Kemba

Reputation: 29

Filter Object Array

This is the code:

var displayedYearDataCo2 = getYearFromObjectArray(dumpObjectArray);

var dumpObjectArray = [{
2000: "3861703.86265837",
2001: "3948395.50088809",
2002: "4079614.75274644",
2003: "4243914.23578233",
2004: "4473182.3714518",
2005: "4666976.64129297",
2006: "4912930.11306349",
2007: "5230542.3962404",
2008: "5447541.9024238",
2009: "5614275.08094141",
2010: "5873859.25045115"},
{2000: "6445883.82450361",
2001: "6500776.94950847",
2002: "6510827.66224668",
2003: "6702943.57911293",
2004: "6732003.46639188",
2005: "6712282.82564533",
2006: "6846499.23063543",
2007: "6837383.17387017",
2008: "6810185.26824634",
2009: "6283177.01076618",
2010: "6544487.27529572"}];

function getYearFromObjectArray(value){
  var objArrOnlySelectedYear = dumpObjectArray.filter(d => d.key === value);
  return objArrOnlySelectedYear;
};

Instead of filtering and returning objects with value in question I get following error notification:

Uncaught TypeError: Cannot read properties of undefined (reading 'filter') at getYearFromObjectArray

update:
Thank you all so much for helping me better understand and hence formulate my question better. Function getYearFromObjectArray() should return all the corresponding values of keys of the dumpObjectArray. For example getYearFromObjectArray(2007) or maybe it is getYearFromObjectArray("2007") should return ["5230542.3962404","6837383.17387017"] in this case. I need this for constructing a D3 scatterplot where the data comes from a CSV file.

Upvotes: 0

Views: 44

Answers (1)

Mina
Mina

Reputation: 17139

I think this is what you are looking for to search for the object that has a value equal to the value parameter.

var dumpObjectArray = [{
2000: "3861703.86265837",
2001: "3948395.50088809",
2002: "4079614.75274644",
2003: "4243914.23578233",
2004: "4473182.3714518",
2005: "4666976.64129297",
2006: "4912930.11306349",
2007: "5230542.3962404",
2008: "5447541.9024238",
2009: "5614275.08094141",
2010: "5873859.25045115"},
{2000: "6445883.82450361",
2001: "6500776.94950847",
2002: "6510827.66224668",
2003: "6702943.57911293",
2004: "6732003.46639188",
2005: "6712282.82564533",
2006: "6846499.23063543",
2007: "6837383.17387017",
2008: "6810185.26824634",
2009: "6283177.01076618",
2010: "6544487.27529572"}];

function getYearFromObjectArray(value){
  return dumpObjectArray.filter(d => Object.values(d).find(i => i === value));
};

var displayedYearDataCo2 = getYearFromObjectArray("6544487.27529572");

console.log(displayedYearDataCo2)

Upvotes: 2

Related Questions