1

In my current scenario, I would like to remove the level of index numbers from an array. Since the keys are not fixed and may change from time to time, it will affect my script in the long run.

I have found code that does the job using PHP. But how can I do it in JS?

PHP

$newArray = array();

foreach($value as $val) {
    $newArray = array_merge($new, $val);
}

JS

var newArray = [];

oldArray.forEach(function(entry){
    newArray = newArray.concat(entry);
});

PHP SAMPLE DATA AND RESULT

array(3) {
[0]=>
   array(1) {
      ["name"]=>
      string(8) "John Doe"
   }
[1]=>
   array(1) {
      ["age"]=>
      string(2) "24"
   }
[2]=>
   array(1) {
      ["sex"]=>
      string(4) "male"
  }
}

TO THIS

array(3) {
["name"]=>
      string(8) "John Doe"
["age"]=>
      string(2) "24"
["sex"]=>
      string(4) "male"
}

Above samples are from PHP output which I also want to attain in JS.

With my code in js, it is not removing the level of indexes of the array. I want to remove the indexes of the array so that I get a plain object in which I can access its data like newArray['name'] without passing through an index since its arrangement is unpredictable.

Please let me know if you have clarifications for I really need your help on this.

trincot
  • 317,000
  • 35
  • 244
  • 286
Eem Jee
  • 1,239
  • 5
  • 30
  • 64
  • 1
    Why don't you use an object instead? With the object you can change the keys to whatever you want and you can access them that way: newArray['name'] – Stundji Dec 11 '18 at 07:39
  • @trincot I provide PHP code for that is the other code I have in my php end and is relatable to my JS situation which I don't have yet. – Eem Jee Dec 11 '18 at 07:39
  • @Stundji Thanks man! I have just converted my data to object and do it :) which is also an answer of trincot below. – Eem Jee Dec 11 '18 at 07:44
  • The sample data in JS format is missing. We have to guess what it is based on the PHP sample. – trincot Dec 11 '18 at 07:44

1 Answers1

2

If your data is like the PHP sample data, it will be an array of plain objects, where each object has one property.

In that case use Object.assign with the spread syntax:

const oldArray = [ {"age": 13}, {"length": 8} ];

const newArray = Object.assign({}, ...oldArray);

console.log(newArray);
trincot
  • 317,000
  • 35
  • 244
  • 286