Converting array and objects in array to pure array
Have you tried typecasting?
$array = (array) $object;
There is another trick actually$json = json_encode($object);
$array = json_decode($json, true);
You can have more info here json_decode
in the PHP manual, the second parameter is called assoc:assocWhich is exactly what you're looking for.When
TRUE
, returned objects will be converted into associative arrays.
You may want to try this, too : Convert Object To Array With PHP (phpro.org)
Convert Array to Object
ECMAScript 6 introduces the easily polyfillable Object.assign
:
TheObject.assign()
method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length
property of the array is not copied because it isn't enumerable.Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
For custom keys you can use reduce:['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }
Javascript convert array of objects to an array with only specific keys with ES6
Use the function reduce
because the function map
returns an array with the same length of the source array.
const finalarr = arr.reduce((a, {value}) => {
if (value) a.push(value);
return a;
}, []);
Important: your approach is skipping the objects with values equal to zero 0
.Example
const arr = [{name:'one', value:1},{name:'two'},{name:'three', value:3}];const finalarr = arr.reduce((a, {value}) => { if (value) a.push(value); return a;}, []);console.log(finalarr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Convert an array of objects into a nested array of objects based on string property?
Using Lodash (because why on earth would you want to manipulate complex data without a utility library). Here's the fiddle.
function formatRoute(route) {
return _.merge(_.pick(route, ['url', 'templateUrl']), {
name: route.name.split('.'),
data: _.pick(route, ['title', 'subtitle']),
children: []
});
}
function getNameLength(route) {
return route.name.length;
}
function buildTree(tree, route) {
var path = _.slice(route.name, 0, -1);
insertAtPath(tree, path, _.merge({}, route, {
name: _.last(route.name)
}));
return tree;
}
function insertAtPath(children, path, route) {
var head = _.first(path);
var match = _.find(children, function (child) {
return child.name === head;
});
if (path.length === 0) {
children.push(route);
}
else {
if (!match) {
match = {
name: head,
data: {},
children: []
};
children.push(match);
}
insertAtPath(match.children, _.rest(path), route);
}
}
// Map the routes into their correct formats.
var routes = _.sortBy(_.map(input, formatRoute), getNameLength);
// Now we can reduce this well formatted array into the desired format.
var out = _.reduce(routes, buildTree, []);
It works by reshaping the initial input so as to split the names into arrays and add the data / children properties. Then it reduces the data over buildTree
which uses a mutating function ( :( ) to insert the current item in the reduce at the given path.The strange if (!match)
part makes sure that missing segments are added in if they're not explicitly specified in the initial data set with a URL etc.
The last two lines that actually do the work should probably be in a little function, and it could do with some JSDoc. It's just a shame I didn't get it completely recursive, I'm relying on array mutation to insert the route object deep within the tree.
Should be simple enough to follow though.
How to map array of values to an array of objects
You can do it like this with Array.prototype.map():
const arr = ['tree', 'apple', 'orange'];
const result = arr.map(value => ({ value }));
console.log(result);
How to convert convert object to array
You can use the property directly for the return value.
var array = [{ "itemCode": "Mob-mtr" }, { "itemCode": "640-chr" }], result = array.map(function (a) { return a.itemCode; });
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Convert array of objects to one Object using ramda.js
With plain Javascript, you could use a combination with Object.assign
, spread syntax ...
, Array#map
, destructuring assignment and short hand properties.
var a = [{ id: 1, val: 'a' }, { id: 2, val: 'b' }, { id: 3, val: 'c' }, { id: 4, val: 'd' }], result = Object.assign(...a.map(({ id, val }) => ({ [id]: val })));
console.log(result);
Related Topics
Typecasting VS Function to Convert Variable Type in PHP
PHP MySQL - Insert into Without Using Column Names But with Autoincrement Field
How to Make a Chat Room Script with PHP
Use MySQL_Fetch_Array() with Foreach() Instead of While()
Get Query Back from Pdo Prepared Statement
PHP Class Not Found But It's Included
Add a Custom Checkbox in Woocommerce Checkout Which Value Shows in Admin Edit Order
PHP Warning: Unknown: Input Variables Exceeded 1000
Iterate in Reverse Through an Array with PHP - Spl Solution
Setting PHP Enviromental Variable While Running Command Line Script
How to Use a PHP Class from Another File
Laravel Catch Eloquent "Unique" Field Error
Php: How to Set Current Working Directory to Be Same as Directory Executing the Script
How to Remove Email Addresses and Links from a String in PHP