Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Split and return array in multiple arrays or string

I have a json like this:

{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"}]}}

... and I dynamically fetch the values and create a variable this:

var existingParams = [
"name",
"updated"].filter(field => getBody.search[field]);

var sqlVal = existingParams.map(field => {
 if (field === 'name') {
     function getValues(item, index) {
       var getVal = [item.tag];
       return "%" + getVal + "%";
     }
     console.log(name.map(getValues));
     return name.map(getValues);

   } else {
     return getBody.search[field];
   }
 })

For the above example I get for sqlVal:

console.log(sqlVal);         

[ [ '%Peter%' ], '2018-11-07' ]

... which is fine.

BUT, if I have two values:

{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"}]}} 

... I'm getting this structure:

[ [ '%Peter%', '%Jack%' ], '2018-11-07' ]   

... but what I need is sth like:

[ '%Peter%', '%Jack%', '2018-11-07' ]

... or:

[ ['%Peter%'], ['%Jack%'], '2018-11-07' ]

And in case of further e.g. 3 names:

{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"},{"tag":"Maria"}]}} 

... I need sth like:

[ '%Peter%', '%Jack%', '%Maria%', '2018-11-07' ]        

... or:

[ ['%Peter%'], ['%Jack%'], ['%Maria%'], '2018-11-07' ]

... and so on

How do I need to adjust the above query to get this?

like image 212
Philipp M Avatar asked Dec 11 '25 07:12

Philipp M


1 Answers

If I understand your question correctly, then this problem can be solved via the Array#reduce() method.

The general idea with this approach is to transform your input object to an array - the reduce operation can be used to do this, with the special-case rule of "flattening" the nested value on the name key into the final result:

var input = {"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"}]}}

var result = Object
.entries(input.search)
.reduce(function(result, entry) {

  const key = entry[0]
  const value = entry[1]
  
  if(key === 'name') {

    // When the 'name' key is encountered, handle the value
    // differently, by addting the items of this value array
    // to the result
    value.forEach(function(item) { 
      result.push('%' + item.tag + '%')
    })
  }
  else {
  
    // Append values for other keys directly to the result
    result.push(value)
  }
  
  return result
  
}, [])

console.log(result )
like image 147
Dacre Denny Avatar answered Dec 13 '25 19:12

Dacre Denny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!