Home > Software engineering >  Convert multidimensional array into one array in Javascript
Convert multidimensional array into one array in Javascript

Time:11-21

I have multidimensional array. And I want it to be a single array Also I found solution in php code. Php Code below

$array = [
'pg1' => '23',
'pg_123'=> '342443',
'pg_1_2' => '25',
'pg-123' => 'test',
'pg321' => 'grgerhgre',
];


function makeFlatParamsArray($arrParams, $parent_name = '')
{
$arrFlatParams = [];
$i = 0;
foreach ($arrParams as $key => $val) {
    $i  ;
    $name = $parent_name . $key . sprintf('d', $i);
    if (is_array($val)) {
        $arrFlatParams = array_merge($arrFlatParams, makeFlatParamsArray($val, $name));
        continue;
    }
    $arrFlatParams  = array($name => (string)$val);
}

return $arrFlatParams;
}

$newArr = makeFlatParamsArray($array);
echo $newArr;

Output: pg1001 23; pg_123002 342443; pg_1_2003 25; pg-123004 test; pg321005 grgerhgre;

How to convert php code above to javascript. Can you help me?

CodePudding user response:

This should give your expected result:

const padZeros = (num, places) => String(num).padStart(places, '0');

inputArray = {
  pg1: '23',
  pg_123: '342443',
  pg_1_2: '25',
  'pg-123': 'test',
  pg321: 'grgerhgre',
};

var resultArray = [];
var index = 0;
for (var key in inputArray) {
  resultArray.push(key   padZeros(  index, 3)   ' '   inputArray[key]);
}

console.log('result', resultArray) // OK

Or, a more compact version, using Object.keys and reduce:

var resultArray = Object.keys(inputArray).reduce((acc, key, i) => {
  acc.push(key   padZeros(i   1, 3)   ' '   inputArray[key]);
  return acc;
}, []);

console.log('result', resultArray) // OK
  • Related