Home > Net >  Nested array sorting for bulk data
Nested array sorting for bulk data

Time:01-07

I have the following data as a nested array please see the below fiddle https://jsfiddle.net/athulmathew/z3s1w0mu/ I want to get the output from the array-like below

var item {caller_number_raw : data from the array,company_id:data from the array}

I tried to sort it like this

for (i in data.data.hits) {
  for (j in data.data.hits[i]._source) {   
    //str  = data.data.hits[i]._source[j]   "<br/>";
    var Item ={CallerID:data.data.hits[i]._source[j].caller_number}       
    console.log(Item) 
  }
}

but returns an empty object "{}" I am not that familiar with nested arrays can anybody help me what I am doing wrong here

CodePudding user response:

_source is just an Object, you don't have to iterate over its property in order to get a specific property, you can replace the second loop with just var Item ={CallerID:data.data.hits[i]._source.caller_number} .

Also, since data.data.hits is an array, it is more appropriate to use for...of or a normal for loop instead of for...in.

Here is an example:

for (const hit of data.data.hits) {
    const item = { CallerID: hit._source.caller_number };
    console.log(item);
}

Event though the example above will work, it will not produce the required output the you've mentioned, to do that, you can use something like this:

for (const hit of data.data.hits) {
    const item = { caller_number_raw : hit.caller_number_raw, company_id: hit.company_id }
    console.log(item);
}

If you want to store all the newly created objects into an array, you can do something like this:

const output = [];
for (const hit of data.data.hits) {
    output.push({ caller_number_raw : hit.caller_number_raw, company_id: hit.company_id });
}
console.log(output);

This is even easier using a functional approach:

const output = data.data.hits.map(({ caller_number_raw, company_id }) => ({ caller_number_raw, company_id }));

CodePudding user response:

here you don't need the second for in loop because _source is an object.

for (let i in data.data.hits) {
    if(data.data.hits[i]._source.caller_number){
      var Item = {
        CallerID: data.data.hits[i]._source.caller_number
      }
       console.log(Item)
    }
   
}

Here is the jsFiddle link of the solution.

  •  Tags:  
  • Related