Convert Multidimensional Objects to Array

Convert multidimensional objects to array

You can use recursive function like below:

function object_to_array($obj, &$arr)
{
if (!is_object($obj) && !is_array($obj))
{
$arr = $obj;
return $arr;
}

foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
objToArray($value, $arr[$key]);
}
else {$arr[$key] = $value;}
}

return $arr;
}

Reduce multi-dimensional array of objects into a single array of object

function tranform(array) {  const obj = {}    array.forEach(({name, value}) => (value || []).forEach(({id, data}) => obj[id] = { id, ...obj[id], [name]: data } ))    return Object.values(obj)}
const initialArray = [ { name: 'aaa', value:[{id:1, data:1}, {id:2, data:2}, {id:3, data:3}] }, { name: 'bbb', value:[{id:1, data:4}, {id:2, data:5}, {id:3, data:6}] }, { name: 'ccc', value:[{id:1, data:7}, {id:2, data:8}, {id:3, data:7}] }, { name: 'ddd', value:[{id:1, data:2}, {id:2, data:1}, {id:3, data:1}] }]
console.log(tranform(initialArray))

Convert object to multi-dimensional array - JavaScript

You can use Object.entries function.

var myObj = { a: 1, b: 2, c: 3, d: 4 },    myArray = Object.entries(myObj);        console.log(JSON.stringify(myArray));

Converting multidimensional object to array

Your object's properties are private. If you var_dump() an object as you did it prints also private properties.

Have a look at this article http://php.net/manual/en/language.oop5.iterations.php. You can iterate object as you do but it iterates only public properties.

Convert array of Objects to 2d array

You could use map

var tags= [ {id: 0, name: "tag1", project: "p1", bu: "test"}, {id: 1, name: "tag2", project: "p1", bu: "test"}, {id: 2, name: "tag3", project: "p3", bu: "test"} ];
var res=tags.map(o=>[o.name,o.project,o.bu])
console.log(res)

Convert Array of Objects to Multi Dimensional Array in JavaScript

You can use array#map. Iterate through each object and create an array.

var data = [{firstName: "John",lastName: "Doe",age: 46},{firstName: "Mike",lastName: "Jeffrey",age: 56}],    result = data.map(o => [o]);console.log(result);

converting two-dimensional array into array object in JavaScript

The difference between the two depends a lot on the environment that the Javascript is being run in. Lets just see:

http://jsperf.com/array-vs-object-lookup-986

Running that in chrome V8, you can see the difference is notable, with a edge to a map lookup. The map lookup notation is also vastly more maintainable for future devs who have to work on your code.

Edit: The map way is 5x faster FF.



Related Topics



Leave a reply



Submit