Home > Enterprise >  Get the object that has a certain number in it from an object within an object
Get the object that has a certain number in it from an object within an object

Time:07-27

I make an API call and it gives back the following:

[
  [1529539200,15.9099,16.15,15.888,16.0773,84805.7,1360522.8], 
  [1529625600,16.0768,17.38,15.865,17.0727,3537945.2,58937516], 
  [1529712000,17.0726,17.25,15.16,15.56,3363347.2,54172164], 
  [1529798400,15.55,16.0488,15.3123,15.6398,2103994.8,33027598], 
  [1529884800,15.6024,15.749,13.3419,14.4174,3863905.2,55238030], 
  [1529971200,14.4174,15.1532,13.76,14.8982,2266159.8,33036208],
  ...
]

There are basically about 1000 objects in total, and every object has 7 objects within it, each of them containing the values shown above. Right now I have set

var objects= response.data.result[86400] 

which gives the result you see above, and now, I need to search through these objects until Javascript finds the object that has the value '1529884800' in object zero, so for example with the code above this would result in this number:

object[5][0]

I wrote the following ode but it doesn't work, results in an empty array as response.

var results = [];

var toSearch = 1529539200;

for (var i=0; i<objects.length; i  ) {
  for (key in objects[i][0]) {
    if (objects[i][key].indexOf(toSearch) != -1) {
      results.push(objects[i]);
    }
    console.log(results)
  }
}
(in the above results just shows []) I tried doing var toSerach ='1529539200' and without quotes but neither work, what is the issue here? Would appreciate any help, thanks

CodePudding user response:

If you want the index of a given number, use .flatMap() and .indexOf()

First iterate through the outer array

array.flatMap((sub, idx) =>

Then on each sub-array find the index of the given number. .indexOf() will either return the index of the number if it exists or -1 if it doesn't. In the final return it will be the index number of the sub-array and then the index of the number within the sub-array if found. Otherwise an empty array is returned which results in nothing because .flatMap() flattens arrays by one level.

sub.indexOf(number) > -1 ? [idx, sub.indexOf(number)] : []) 

const data = [[1529539200,15.9099,16.15,15.888,16.0773,84805.7,1360522.8],[1529625600,16.0768,17.38,15.865,17.0727,3537945.2,58937516],[1529712000,17.0726,17.25,15.16,15.56,3363347.2,54172164],[1529798400,15.55,16.0488,15.3123,15.6398,2103994.8,33027598],[1529884800,15.6024,15.749,13.3419,14.4174,3863905.2,55238030],[1529971200,14.4174,15.1532,13.76,14.8982,2266159.8,33036208]];

let A = 1529539200;
let B = 33036208;
let C = 15.16;

const findNumber = (array, number) => 
  array.flatMap((sub, idx) => 
  sub.indexOf(number) > -1 ? [idx, sub.indexOf(number)] : []) 

console.log(findNumber(data, A));
console.log(findNumber(data, B));
console.log(findNumber(data, C));

  • Related