Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Convert multidimensional array into one array in Javascript

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('%03d', $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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!