Substitube for lodash transform on an object [duplicate] - javascript

I have an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
I am looking for a native method, similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
Does JavaScript have such a map function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)

There is no native map to the Object object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
But you could easily iterate over an object using for ... in:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
console.log(myObject);
// { 'a': 2, 'b': 4, 'c': 6 }
Update
A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
// returns a new object with the values at each key mapped using mapFn(value)
function objectMap(object, mapFn) {
return Object.keys(object).reduce(function(result, key) {
result[key] = mapFn(object[key])
return result
}, {})
}
var newObject = objectMap(myObject, function(value) {
return value * 2
})
console.log(newObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }
Array.prototype.reduce reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object {}. On every iteration a new key of myObject is added with twice the key as the value.
Update
With new ES6 features, there is a more elegant way to express objectMap.
const objectMap = (obj, fn) =>
Object.fromEntries(
Object.entries(obj).map(
([k, v], i) => [k, fn(v, k, i)]
)
)
const myObject = { a: 1, b: 2, c: 3 }
console.log(objectMap(myObject, v => 2 * v))

How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries() and Object.fromEntries():
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you can't use Objects.fromEntries, but you can achieve the same using Object.assign in combination with spread operators and computed key names syntax:
let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entries, but you could use Object.keys instead:
let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
array.reduce()
Instead of Object.fromEntries and Object.assign you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
Inherited properties and the prototype chain:
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys() and Object.entries() won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)

No native methods, but lodash#mapValues will do the job brilliantly
_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
// → { 'a': 3, 'b': 6, 'c': 9 }

It's pretty easy to write one:
Object.map = function(o, f, ctx) {
ctx = ctx || this;
var result = {};
Object.keys(o).forEach(function(k) {
result[k] = f.call(ctx, o[k], k, o);
});
return result;
}
with example code:
> o = { a: 1, b: 2, c: 3 };
> r = Object.map(o, function(v, k, o) {
return v * v;
});
> r
{ a : 1, b: 4, c: 9 }
NB: this version also allows you to (optionally) set the this context for the callback, just like the Array method.
EDIT - changed to remove use of Object.prototype, to ensure that it doesn't clash with any existing property named map on the object.

You could use Object.keys and then forEach over the returned array of keys:
var myObject = { 'a': 1, 'b': 2, 'c': 3 },
newObject = {};
Object.keys(myObject).forEach(function (key) {
var value = myObject[key];
newObject[key] = value * value;
});
Or in a more modular fashion:
function map(obj, callback) {
var result = {};
Object.keys(obj).forEach(function (key) {
result[key] = callback.call(obj, obj[key], key, obj);
});
return result;
}
newObject = map(myObject, function(x) { return x * x; });
Note that Object.keys returns an array containing only the object's own enumerable properties, thus it behaves like a for..in loop with a hasOwnProperty check.

This is really annoying, and everyone in the JS community knows it. There should be this functionality:
const obj1 = {a:4, b:7};
const obj2 = Object.map(obj1, (k,v) => v + 5);
console.log(obj1); // {a:4, b:7}
console.log(obj2); // {a:9, b:12}
here is the naïve implementation:
Object.map = function(obj, fn, ctx){
const ret = {};
for(let k of Object.keys(obj)){
ret[k] = fn.call(ctx || null, k, obj[k]);
});
return ret;
};
it is super annoying to have to implement this yourself all the time ;)
If you want something a little more sophisticated, that doesn't interfere with the Object class, try this:
let map = function (obj, fn, ctx) {
return Object.keys(obj).reduce((a, b) => {
a[b] = fn.call(ctx || null, b, obj[b]);
return a;
}, {});
};
const x = map({a: 2, b: 4}, (k,v) => {
return v*2;
});
but it is safe to add this map function to Object, just don't add to Object.prototype.
Object.map = ... // fairly safe
Object.prototype.map ... // not ok

I came here looking to find and answer for mapping an object to an array and got this page as a result. In case you came here looking for the same answer I was, here is how you can map and object to an array.
You can use map to return a new array from the object like so:
var newObject = Object.keys(myObject).map(function(key) {
return myObject[key];
});

Minimal version
ES2017
Object.entries(obj).reduce((a, [k, v]) => (a[k] = v * v, a), {})
↑↑↑↑↑
ES2019
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]))
↑↑↑↑↑

JavaScript just got the new Object.fromEntries method.
Example
function mapObject (obj, fn) {
return Object.fromEntries(
Object
.entries(obj)
.map(fn)
)
}
const myObject = { a: 1, b: 2, c: 3 }
const myNewObject = mapObject(myObject, ([key, value]) => ([key, value * value]))
console.log(myNewObject)
Explanation
The code above converts the Object into an nested Array ([[<key>,<value>], ...]) wich you can map over. Object.fromEntries converts the Array back to an Object.
The cool thing about this pattern, is that you can now easily take object keys into account while mapping.
Documentation
Object.fromEntries()
Object.entries()
Browser Support
Object.fromEntries is currently only supported by these browsers/engines, nevertheless there are polyfills available (e.g #babel/polyfill).

The accepted answer has two drawbacks:
It misuses Array.prototype.reduce, because reducing means to change the structure of a composite type, which doesn't happen in this case.
It is not particularly reusable
An ES6/ES2015 functional approach
Please note that all functions are defined in curried form.
// small, reusable auxiliary functions
const keys = o => Object.keys(o);
const assign = (...o) => Object.assign({}, ...o);
const map = f => xs => xs.map(x => f(x));
const mul = y => x => x * y;
const sqr = x => mul(x) (x);
// the actual map function
const omap = f => o => {
o = assign(o); // A
map(x => o[x] = f(o[x])) (keys(o)); // B
return o;
};
// mock data
const o = {"a":1, "b":2, "c":3};
// and run
console.log(omap(sqr) (o));
console.log(omap(mul(10)) (o));
In line A o is reassigned. Since Javascript passes reference values by sharing, a shallow copy of o is generated. We are now able to mutate o within omap without mutating o in the parent scope.
In line B map's return value is ignored, because map performs a mutation of o. Since this side effect remains within omap and isn't visible in the parent scope, it is totally acceptable.
This is not the fastest solution, but a declarative and reusable one. Here is the same implementation as a one-line, succinct but less readable:
const omap = f => o => (o = assign(o), map(x => o[x] = f(o[x])) (keys(o)), o);
Addendum - why are objects not iterable by default?
ES2015 specified the iterator and iterable protocols. But objects are still not iterable and thus not mappable. The reason is the mixing of data and program level.

For maximum performance.
If your object doesn't change often but needs to be iterated on often I suggest using a native Map as a cache.
// example object
var obj = {a: 1, b: 2, c: 'something'};
// caching map
var objMap = new Map(Object.entries(obj));
// fast iteration on Map object
objMap.forEach((item, key) => {
// do something with an item
console.log(key, item);
});
Object.entries already works in Chrome, Edge, Firefox and beta Opera so it's a future-proof feature.
It's from ES7 so polyfill it https://github.com/es-shims/Object.entries for IE where it doesn't work.

You can convert an object to array simply by using the following:
You can convert the object values to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let valuesArray = Object.values(myObject);
console.log(valuesArray);
You can convert the object keys to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let keysArray = Object.keys(myObject);
console.log(keysArray);
Now you can perform normal array operations, including the 'map' function

you can use map method and forEach on arrays but if you want to use it on Object then you can use it with twist like below:
Using Javascript (ES6)
var obj = { 'a': 2, 'b': 4, 'c': 6 };
Object.entries(obj).map( v => obj[v[0]] *= v[1] );
console.log(obj); //it will log as {a: 4, b: 16, c: 36}
var obj2 = { 'a': 4, 'b': 8, 'c': 10 };
Object.entries(obj2).forEach( v => obj2[v[0]] *= v[1] );
console.log(obj2); //it will log as {a: 16, b: 64, c: 100}
Using jQuery
var ob = { 'a': 2, 'b': 4, 'c': 6 };
$.map(ob, function (val, key) {
ob[key] *= val;
});
console.log(ob) //it will log as {a: 4, b: 16, c: 36}
Or you can use other loops also like $.each method as below example:
$.each(ob,function (key, value) {
ob[key] *= value;
});
console.log(ob) //it will also log as {a: 4, b: 16, c: 36}

The map function does not exist on the Object.prototype however you can emulate it like so
var myMap = function ( obj, callback ) {
var result = {};
for ( var key in obj ) {
if ( Object.prototype.hasOwnProperty.call( obj, key ) ) {
if ( typeof callback === 'function' ) {
result[ key ] = callback.call( obj, obj[ key ], key, obj );
}
}
}
return result;
};
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
var newObject = myMap( myObject, function ( value, key ) {
return value * value;
});

EDIT: The canonical way using newer JavaScript features is -
const identity = x =>
x
const omap = (f = identity, o = {}) =>
Object.fromEntries(
Object.entries(o).map(([ k, v ]) =>
[ k, f(v) ]
)
)
Where o is some object and f is your mapping function. Or we could say, given a function from a -> b, and an object with values of type a, produce an object with values of type b. As a pseudo type signature -
// omap : (a -> b, { a }) -> { b }
The original answer was written to demonstrate a powerful combinator, mapReduce which allows us to think of our transformation in a different way
m, the mapping function – gives you a chance to transform the incoming element before…
r, the reducing function – this function combines the accumulator with the result of the mapped element
Intuitively, mapReduce creates a new reducer we can plug directly into Array.prototype.reduce. But more importantly, we can implement our object functor implementation omap plainly by utilizing the object monoid, Object.assign and {}.
const identity = x =>
x
const mapReduce = (m, r) =>
(a, x) => r (a, m (x))
const omap = (f = identity, o = {}) =>
Object
.keys (o)
.reduce
( mapReduce
( k => ({ [k]: f (o[k]) })
, Object.assign
)
, {}
)
const square = x =>
x * x
const data =
{ a : 1, b : 2, c : 3 }
console .log (omap (square, data))
// { a : 1, b : 4, c : 9 }
Notice the only part of the program we actually had to write is the mapping implementation itself –
k => ({ [k]: f (o[k]) })
Which says, given a known object o and some key k, construct an object and whose computed property k is the result of calling f on the key's value, o[k].
We get a glimpse of mapReduce's sequencing potential if we first abstract oreduce
// oreduce : (string * a -> string * b, b, { a }) -> { b }
const oreduce = (f = identity, r = null, o = {}) =>
Object
.keys (o)
.reduce
( mapReduce
( k => [ k, o[k] ]
, f
)
, r
)
// omap : (a -> b, {a}) -> {b}
const omap = (f = identity, o = {}) =>
oreduce
( mapReduce
( ([ k, v ]) =>
({ [k]: f (v) })
, Object.assign
)
, {}
, o
)
Everything works the same, but omap can be defined at a higher-level now. Of course the new Object.entries makes this look silly, but the exercise is still important to the learner.
You won't see the full potential of mapReduce here, but I share this answer because it's interesting to see just how many places it can be applied. If you're interested in how it is derived and other ways it could be useful, please see this answer.

Object Mapper in TypeScript
I like the examples that use Object.fromEntries such as this one, but still, they are not very easy to use. The answers that use Object.keys and then look up the key are actually doing multiple look-ups that may not be necessary.
I wished there was an Object.map function, but we can create our own and call it objectMap with the ability to modify both key and value:
Usage (JavaScript):
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
// keep the key and modify the value
let obj = objectMap(myObject, val => val * 2);
// obj = { a: 2, b: 4, c: 6 }
// modify both key and value
obj = objectMap(myObject,
val => val * 2 + '',
key => (key + key).toUpperCase());
// obj = { AA: '2', BB: '4', CC: '6' }
Code (TypeScript):
interface Dictionary<T> {
[key: string]: T;
}
function objectMap<TValue, TResult>(
obj: Dictionary<TValue>,
valSelector: (val: TValue, obj: Dictionary<TValue>) => TResult,
keySelector?: (key: string, obj: Dictionary<TValue>) => string,
ctx?: Dictionary<TValue>
) {
const ret = {} as Dictionary<TResult>;
for (const key of Object.keys(obj)) {
const retKey = keySelector
? keySelector.call(ctx || null, key, obj)
: key;
const retVal = valSelector.call(ctx || null, obj[key], obj);
ret[retKey] = retVal;
}
return ret;
}
If you are not using TypeScript then copy the above code in TypeScript Playground to get the JavaScript code.
Also, the reason I put keySelector after valSelector in the parameter list, is because it is optional.
* Some credit go to alexander-mills' answer.

Based on #Amberlamps answer, here's a utility function
(as a comment it looked ugly)
function mapObject(obj, mapFunc){
return Object.keys(obj).reduce(function(newObj, value) {
newObj[value] = mapFunc(obj[value]);
return newObj;
}, {});
}
and the use is:
var obj = {a:1, b:3, c:5}
function double(x){return x * 2}
var newObj = mapObject(obj, double);
//=> {a: 2, b: 6, c: 10}

I came upon this as a first-item in a Google search trying to learn to do this, and thought I would share for other folsk finding this recently the solution I found, which uses the npm package immutable.
I think its interesting to share because immutable uses the OP's EXACT situation in their own documentation - the following is not my own code but pulled from the current immutable-js documentation:
const { Seq } = require('immutable')
const myObject = { a: 1, b: 2, c: 3 }
Seq(myObject).map(x => x * x).toObject();
// { a: 1, b: 4, c: 9 }
Not that Seq has other properties ("Seq describes a lazy operation, allowing them to efficiently chain use of all the higher-order collection methods (such as map and filter) by not creating intermediate collections") and that some other immutable-js data structures might also do the job quite efficiently.
Anyone using this method will of course have to npm install immutable and might want to read the docs:
https://facebook.github.io/immutable-js/

My response is largely based off the highest rated response here and hopefully everyone understands (have the same explanation on my GitHub, too). This is why his impementation with map works:
Object.keys(images).map((key) => images[key] = 'url(' + '"' + images[key] + '"' +
')');
The purpose of the function is to take an object and modify the original contents of the object using a method available to all objects (objects and arrays alike) without returning an array. Almost everything within JS is an object, and for that reason elements further down the pipeline of inheritance can potentially technically use those available to those up the line (and the reverse it appears).
The reason that this works is due to the .map functions returning an array REQUIRING that you provide an explicit or implicit RETURN of an array instead of simply modifying an existing object. You essentially trick the program into thinking the object is an array by using Object.keys which will allow you to use the map function with its acting on the values the individual keys are associated with (I actually accidentally returned arrays but fixed it). As long as there isn't a return in the normal sense, there will be no array created with the original object stil intact and modified as programmed.
This particular program takes an object called images and takes the values of its keys and appends url tags for use within another function. Original is this:
var images = {
snow: 'https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305',
sunny: 'http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-east-
Matanzas-city- Cuba-20170131-1080.jpg',
rain: 'https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg' };
...and modified is this:
var images = {
snow: url('https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305'),
sunny: url('http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-
east-Matanzas-city- Cuba-20170131-1080.jpg'),
rain: url('https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg')
};
The object's original structure is left intact allowing for normal property access as long as there isn't a return. Do NOT have it return an array like normal and everything will be fine. The goal is REASSIGNING the original values (images[key]) to what is wanted and not anything else. As far as I know, in order to prevent array output there HAS to be REASSIGNMENT of images[key] and no implicit or explicit request to return an array (variable assignment does this and was glitching back and forth for me).
EDIT:
Going to address his other method regarding new object creation to avoid modifying original object (and reassignment appears to still be necessary in order to avoid accidentally creating an array as output). These functions use arrow syntax and are if you simply want to create a new object for future use.
const mapper = (obj, mapFn) => Object.keys(obj).reduce((result, key) => {
result[key] = mapFn(obj)[key];
return result;
}, {});
var newImages = mapper(images, (value) => value);
The way these functions work is like so:
mapFn takes the function to be added later (in this case (value) => value) and simply returns whatever is stored there as a value for that key (or multiplied by two if you change the return value like he did) in mapFn(obj)[key],
and then redefines the original value associated with the key in result[key] = mapFn(obj)[key]
and returns the operation performed on result (the accumulator located in the brackets initiated at the end of the .reduce function).
All of this is being performed on the chosen object and STILL there CANNOT be an implicit request for a returned array and only works when reassigning values as far as I can tell. This requires some mental gymnastics but reduces the lines of code needed as can be seen above. Output is exactly the same as can be seen below:
{snow: "https://www.trbimg.com/img-5aa059f5/turbine/bs-
md-weather-20180305", sunny: "http://www.cubaweather.org/images/weather-
photos/l…morning-east-Matanzas-city-Cuba-20170131-1080.jpg", rain:
"https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg"}
Keep in mind this worked with NON-NUMBERS. You CAN duplicate ANY object by SIMPLY RETURNING THE VALUE in the mapFN function.

const mapObject = (targetObject, callbackFn) => {
if (!targetObject) return targetObject;
if (Array.isArray(targetObject)){
return targetObject.map((v)=>mapObject(v, callbackFn))
}
return Object.entries(targetObject).reduce((acc,[key, value]) => {
const res = callbackFn(key, value);
if (!Array.isArray(res) && typeof res ==='object'){
return {...acc, [key]: mapObject(res, callbackFn)}
}
if (Array.isArray(res)){
return {...acc, [key]: res.map((v)=>mapObject(v, callbackFn))}
}
return {...acc, [key]: res};
},{})
};
const mapped = mapObject(a,(key,value)=> {
if (!Array.isArray(value) && key === 'a') return ;
if (!Array.isArray(value) && key === 'e') return [];
if (!Array.isArray(value) && key === 'g') return value * value;
return value;
});
console.log(JSON.stringify(mapped));
// {"b":2,"c":[{"d":2,"e":[],"f":[{"g":4}]}]}
This function goes recursively through the object and arrays of objects. Attributes can be deleted if returned undefined

I needed a version that allowed modifying the keys as well (based on #Amberlamps and #yonatanmn answers);
var facts = [ // can be an object or array - see jsfiddle below
{uuid:"asdfasdf",color:"red"},
{uuid:"sdfgsdfg",color:"green"},
{uuid:"dfghdfgh",color:"blue"}
];
var factObject = mapObject({}, facts, function(key, item) {
return [item.uuid, {test:item.color, oldKey:key}];
});
function mapObject(empty, obj, mapFunc){
return Object.keys(obj).reduce(function(newObj, key) {
var kvPair = mapFunc(key, obj[key]);
newObj[kvPair[0]] = kvPair[1];
return newObj;
}, empty);
}
factObject=
{
"asdfasdf": {"color":"red","oldKey":"0"},
"sdfgsdfg": {"color":"green","oldKey":"1"},
"dfghdfgh": {"color":"blue","oldKey":"2"}
}
Edit: slight change to pass in the starting object {}. Allows it to be [] (if the keys are integers)

var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.prototype.map = function(fn){
var oReturn = {};
for (sCurObjectPropertyName in this) {
oReturn[sCurObjectPropertyName] = fn(this[sCurObjectPropertyName], sCurObjectPropertyName);
}
return oReturn;
}
Object.defineProperty(Object.prototype,'map',{enumerable:false});
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }

If anyone was looking for a simple solution that maps an object to a new object or to an array:
// Maps an object to a new object by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObject = (obj, fn) => {
const newObj = {};
Object.keys(obj).forEach(k => { newObj[k] = fn(k, obj[k]); });
return newObj;
};
// Maps an object to a new array by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObjectToArray = (obj, fn) => (
Object.keys(obj).map(k => fn(k, obj[k]))
);
This may not work for all objects or all mapping functions, but it works for plain shallow objects and straightforward mapping functions which is all I needed.

To responds more closely to what precisely the OP asked for, the OP wants an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
to have a map method myObject.map,
similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
The imho best (measured in terms to "close to what is asked" + "no ES{5,6,7} required needlessly") answer would be:
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
The code above avoids intentionally using any language features, only available in recent ECMAScript editions. With the code above the problem can be solved lke this:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
newObject = myObject.map(function (value, label) {
return value * value;
});
console.log("newObject is now",newObject);
alternative test code here
Besides frowned upon by some, it would be a possibility to insert the solution in the prototype chain like this.
Object.prototype.map = function(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property)){
result[property] = callback(this[property],property,this);
}
}
return result;
}
Something, which when done with careful oversight should not have any ill effects and not impact map method of other objects (i.e. Array's map).

First, convert your HTMLCollection using Object.entries(collection). Then it’s an iterable you can now use the .map method on it.
Object.entries(collection).map(...)
reference
https://medium.com/#js_tut/calling-javascript-code-on-multiple-div-elements-without-the-id-attribute-97ff6a50f31

I handle only strings to reduce exemptions:
Object.keys(params).map(k => typeof params[k] == "string" ? params[k] = params[k].trim() : null);

If you're interested in mapping not only values but also keys, I have written Object.map(valueMapper, keyMapper), that behaves this way:
var source = { a: 1, b: 2 };
function sum(x) { return x + x }
source.map(sum); // returns { a: 2, b: 4 }
source.map(undefined, sum); // returns { aa: 1, bb: 2 }
source.map(sum, sum); // returns { aa: 2, bb: 4 }

Hey wrote a little mapper function that might help.
function propertyMapper(object, src){
for (var property in object) {
for (var sourceProp in src) {
if(property === sourceProp){
if(Object.prototype.toString.call( property ) === '[object Array]'){
propertyMapper(object[property], src[sourceProp]);
}else{
object[property] = src[sourceProp];
}
}
}
}
}

A different take on it is to use a custom json stringify function that can also work on deep objects. This might be useful if you intend to post it to the server anyway as json
const obj = { 'a': 1, 'b': 2, x: {'c': 3 }}
const json = JSON.stringify(obj, (k, v) => typeof v === 'number' ? v * v : v)
console.log(json)
console.log('back to json:', JSON.parse(json))

I needed a function to optionally map not only (nor exclusively) values, but also keys. The original object should not change. The object contained only primitive values also.
function mappedObject(obj, keyMapper, valueMapper) {
const mapped = {};
const keys = Object.keys(obj);
const mapKey = typeof keyMapper == 'function';
const mapVal = typeof valueMapper == 'function';
for (let i = 0; i < keys.length; i++) {
const key = mapKey ? keyMapper(keys[i]) : keys[i];
const val = mapVal ? valueMapper(obj[keys[i]]) : obj[keys[i]];
mapped[key] = val;
}
return mapped;
}
Use. Pass a keymapper and a valuemapper function:
const o1 = { x: 1, c: 2 }
mappedObject(o1, k => k + '0', v => v + 1) // {x0: 2, c0: 3}

Related

Why is returning only one object in for in loop [duplicate]

I have an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
I am looking for a native method, similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
Does JavaScript have such a map function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)
There is no native map to the Object object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
But you could easily iterate over an object using for ... in:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
console.log(myObject);
// { 'a': 2, 'b': 4, 'c': 6 }
Update
A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
// returns a new object with the values at each key mapped using mapFn(value)
function objectMap(object, mapFn) {
return Object.keys(object).reduce(function(result, key) {
result[key] = mapFn(object[key])
return result
}, {})
}
var newObject = objectMap(myObject, function(value) {
return value * 2
})
console.log(newObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }
Array.prototype.reduce reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object {}. On every iteration a new key of myObject is added with twice the key as the value.
Update
With new ES6 features, there is a more elegant way to express objectMap.
const objectMap = (obj, fn) =>
Object.fromEntries(
Object.entries(obj).map(
([k, v], i) => [k, fn(v, k, i)]
)
)
const myObject = { a: 1, b: 2, c: 3 }
console.log(objectMap(myObject, v => 2 * v))
How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries() and Object.fromEntries():
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you can't use Objects.fromEntries, but you can achieve the same using Object.assign in combination with spread operators and computed key names syntax:
let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entries, but you could use Object.keys instead:
let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
array.reduce()
Instead of Object.fromEntries and Object.assign you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
Inherited properties and the prototype chain:
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys() and Object.entries() won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)
No native methods, but lodash#mapValues will do the job brilliantly
_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
// → { 'a': 3, 'b': 6, 'c': 9 }
It's pretty easy to write one:
Object.map = function(o, f, ctx) {
ctx = ctx || this;
var result = {};
Object.keys(o).forEach(function(k) {
result[k] = f.call(ctx, o[k], k, o);
});
return result;
}
with example code:
> o = { a: 1, b: 2, c: 3 };
> r = Object.map(o, function(v, k, o) {
return v * v;
});
> r
{ a : 1, b: 4, c: 9 }
NB: this version also allows you to (optionally) set the this context for the callback, just like the Array method.
EDIT - changed to remove use of Object.prototype, to ensure that it doesn't clash with any existing property named map on the object.
You could use Object.keys and then forEach over the returned array of keys:
var myObject = { 'a': 1, 'b': 2, 'c': 3 },
newObject = {};
Object.keys(myObject).forEach(function (key) {
var value = myObject[key];
newObject[key] = value * value;
});
Or in a more modular fashion:
function map(obj, callback) {
var result = {};
Object.keys(obj).forEach(function (key) {
result[key] = callback.call(obj, obj[key], key, obj);
});
return result;
}
newObject = map(myObject, function(x) { return x * x; });
Note that Object.keys returns an array containing only the object's own enumerable properties, thus it behaves like a for..in loop with a hasOwnProperty check.
This is really annoying, and everyone in the JS community knows it. There should be this functionality:
const obj1 = {a:4, b:7};
const obj2 = Object.map(obj1, (k,v) => v + 5);
console.log(obj1); // {a:4, b:7}
console.log(obj2); // {a:9, b:12}
here is the naïve implementation:
Object.map = function(obj, fn, ctx){
const ret = {};
for(let k of Object.keys(obj)){
ret[k] = fn.call(ctx || null, k, obj[k]);
});
return ret;
};
it is super annoying to have to implement this yourself all the time ;)
If you want something a little more sophisticated, that doesn't interfere with the Object class, try this:
let map = function (obj, fn, ctx) {
return Object.keys(obj).reduce((a, b) => {
a[b] = fn.call(ctx || null, b, obj[b]);
return a;
}, {});
};
const x = map({a: 2, b: 4}, (k,v) => {
return v*2;
});
but it is safe to add this map function to Object, just don't add to Object.prototype.
Object.map = ... // fairly safe
Object.prototype.map ... // not ok
I came here looking to find and answer for mapping an object to an array and got this page as a result. In case you came here looking for the same answer I was, here is how you can map and object to an array.
You can use map to return a new array from the object like so:
var newObject = Object.keys(myObject).map(function(key) {
return myObject[key];
});
Minimal version
ES2017
Object.entries(obj).reduce((a, [k, v]) => (a[k] = v * v, a), {})
↑↑↑↑↑
ES2019
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]))
↑↑↑↑↑
JavaScript just got the new Object.fromEntries method.
Example
function mapObject (obj, fn) {
return Object.fromEntries(
Object
.entries(obj)
.map(fn)
)
}
const myObject = { a: 1, b: 2, c: 3 }
const myNewObject = mapObject(myObject, ([key, value]) => ([key, value * value]))
console.log(myNewObject)
Explanation
The code above converts the Object into an nested Array ([[<key>,<value>], ...]) wich you can map over. Object.fromEntries converts the Array back to an Object.
The cool thing about this pattern, is that you can now easily take object keys into account while mapping.
Documentation
Object.fromEntries()
Object.entries()
Browser Support
Object.fromEntries is currently only supported by these browsers/engines, nevertheless there are polyfills available (e.g #babel/polyfill).
The accepted answer has two drawbacks:
It misuses Array.prototype.reduce, because reducing means to change the structure of a composite type, which doesn't happen in this case.
It is not particularly reusable
An ES6/ES2015 functional approach
Please note that all functions are defined in curried form.
// small, reusable auxiliary functions
const keys = o => Object.keys(o);
const assign = (...o) => Object.assign({}, ...o);
const map = f => xs => xs.map(x => f(x));
const mul = y => x => x * y;
const sqr = x => mul(x) (x);
// the actual map function
const omap = f => o => {
o = assign(o); // A
map(x => o[x] = f(o[x])) (keys(o)); // B
return o;
};
// mock data
const o = {"a":1, "b":2, "c":3};
// and run
console.log(omap(sqr) (o));
console.log(omap(mul(10)) (o));
In line A o is reassigned. Since Javascript passes reference values by sharing, a shallow copy of o is generated. We are now able to mutate o within omap without mutating o in the parent scope.
In line B map's return value is ignored, because map performs a mutation of o. Since this side effect remains within omap and isn't visible in the parent scope, it is totally acceptable.
This is not the fastest solution, but a declarative and reusable one. Here is the same implementation as a one-line, succinct but less readable:
const omap = f => o => (o = assign(o), map(x => o[x] = f(o[x])) (keys(o)), o);
Addendum - why are objects not iterable by default?
ES2015 specified the iterator and iterable protocols. But objects are still not iterable and thus not mappable. The reason is the mixing of data and program level.
For maximum performance.
If your object doesn't change often but needs to be iterated on often I suggest using a native Map as a cache.
// example object
var obj = {a: 1, b: 2, c: 'something'};
// caching map
var objMap = new Map(Object.entries(obj));
// fast iteration on Map object
objMap.forEach((item, key) => {
// do something with an item
console.log(key, item);
});
Object.entries already works in Chrome, Edge, Firefox and beta Opera so it's a future-proof feature.
It's from ES7 so polyfill it https://github.com/es-shims/Object.entries for IE where it doesn't work.
You can convert an object to array simply by using the following:
You can convert the object values to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let valuesArray = Object.values(myObject);
console.log(valuesArray);
You can convert the object keys to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let keysArray = Object.keys(myObject);
console.log(keysArray);
Now you can perform normal array operations, including the 'map' function
you can use map method and forEach on arrays but if you want to use it on Object then you can use it with twist like below:
Using Javascript (ES6)
var obj = { 'a': 2, 'b': 4, 'c': 6 };
Object.entries(obj).map( v => obj[v[0]] *= v[1] );
console.log(obj); //it will log as {a: 4, b: 16, c: 36}
var obj2 = { 'a': 4, 'b': 8, 'c': 10 };
Object.entries(obj2).forEach( v => obj2[v[0]] *= v[1] );
console.log(obj2); //it will log as {a: 16, b: 64, c: 100}
Using jQuery
var ob = { 'a': 2, 'b': 4, 'c': 6 };
$.map(ob, function (val, key) {
ob[key] *= val;
});
console.log(ob) //it will log as {a: 4, b: 16, c: 36}
Or you can use other loops also like $.each method as below example:
$.each(ob,function (key, value) {
ob[key] *= value;
});
console.log(ob) //it will also log as {a: 4, b: 16, c: 36}
The map function does not exist on the Object.prototype however you can emulate it like so
var myMap = function ( obj, callback ) {
var result = {};
for ( var key in obj ) {
if ( Object.prototype.hasOwnProperty.call( obj, key ) ) {
if ( typeof callback === 'function' ) {
result[ key ] = callback.call( obj, obj[ key ], key, obj );
}
}
}
return result;
};
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
var newObject = myMap( myObject, function ( value, key ) {
return value * value;
});
EDIT: The canonical way using newer JavaScript features is -
const identity = x =>
x
const omap = (f = identity, o = {}) =>
Object.fromEntries(
Object.entries(o).map(([ k, v ]) =>
[ k, f(v) ]
)
)
Where o is some object and f is your mapping function. Or we could say, given a function from a -> b, and an object with values of type a, produce an object with values of type b. As a pseudo type signature -
// omap : (a -> b, { a }) -> { b }
The original answer was written to demonstrate a powerful combinator, mapReduce which allows us to think of our transformation in a different way
m, the mapping function – gives you a chance to transform the incoming element before…
r, the reducing function – this function combines the accumulator with the result of the mapped element
Intuitively, mapReduce creates a new reducer we can plug directly into Array.prototype.reduce. But more importantly, we can implement our object functor implementation omap plainly by utilizing the object monoid, Object.assign and {}.
const identity = x =>
x
const mapReduce = (m, r) =>
(a, x) => r (a, m (x))
const omap = (f = identity, o = {}) =>
Object
.keys (o)
.reduce
( mapReduce
( k => ({ [k]: f (o[k]) })
, Object.assign
)
, {}
)
const square = x =>
x * x
const data =
{ a : 1, b : 2, c : 3 }
console .log (omap (square, data))
// { a : 1, b : 4, c : 9 }
Notice the only part of the program we actually had to write is the mapping implementation itself –
k => ({ [k]: f (o[k]) })
Which says, given a known object o and some key k, construct an object and whose computed property k is the result of calling f on the key's value, o[k].
We get a glimpse of mapReduce's sequencing potential if we first abstract oreduce
// oreduce : (string * a -> string * b, b, { a }) -> { b }
const oreduce = (f = identity, r = null, o = {}) =>
Object
.keys (o)
.reduce
( mapReduce
( k => [ k, o[k] ]
, f
)
, r
)
// omap : (a -> b, {a}) -> {b}
const omap = (f = identity, o = {}) =>
oreduce
( mapReduce
( ([ k, v ]) =>
({ [k]: f (v) })
, Object.assign
)
, {}
, o
)
Everything works the same, but omap can be defined at a higher-level now. Of course the new Object.entries makes this look silly, but the exercise is still important to the learner.
You won't see the full potential of mapReduce here, but I share this answer because it's interesting to see just how many places it can be applied. If you're interested in how it is derived and other ways it could be useful, please see this answer.
Object Mapper in TypeScript
I like the examples that use Object.fromEntries such as this one, but still, they are not very easy to use. The answers that use Object.keys and then look up the key are actually doing multiple look-ups that may not be necessary.
I wished there was an Object.map function, but we can create our own and call it objectMap with the ability to modify both key and value:
Usage (JavaScript):
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
// keep the key and modify the value
let obj = objectMap(myObject, val => val * 2);
// obj = { a: 2, b: 4, c: 6 }
// modify both key and value
obj = objectMap(myObject,
val => val * 2 + '',
key => (key + key).toUpperCase());
// obj = { AA: '2', BB: '4', CC: '6' }
Code (TypeScript):
interface Dictionary<T> {
[key: string]: T;
}
function objectMap<TValue, TResult>(
obj: Dictionary<TValue>,
valSelector: (val: TValue, obj: Dictionary<TValue>) => TResult,
keySelector?: (key: string, obj: Dictionary<TValue>) => string,
ctx?: Dictionary<TValue>
) {
const ret = {} as Dictionary<TResult>;
for (const key of Object.keys(obj)) {
const retKey = keySelector
? keySelector.call(ctx || null, key, obj)
: key;
const retVal = valSelector.call(ctx || null, obj[key], obj);
ret[retKey] = retVal;
}
return ret;
}
If you are not using TypeScript then copy the above code in TypeScript Playground to get the JavaScript code.
Also, the reason I put keySelector after valSelector in the parameter list, is because it is optional.
* Some credit go to alexander-mills' answer.
Based on #Amberlamps answer, here's a utility function
(as a comment it looked ugly)
function mapObject(obj, mapFunc){
return Object.keys(obj).reduce(function(newObj, value) {
newObj[value] = mapFunc(obj[value]);
return newObj;
}, {});
}
and the use is:
var obj = {a:1, b:3, c:5}
function double(x){return x * 2}
var newObj = mapObject(obj, double);
//=> {a: 2, b: 6, c: 10}
I came upon this as a first-item in a Google search trying to learn to do this, and thought I would share for other folsk finding this recently the solution I found, which uses the npm package immutable.
I think its interesting to share because immutable uses the OP's EXACT situation in their own documentation - the following is not my own code but pulled from the current immutable-js documentation:
const { Seq } = require('immutable')
const myObject = { a: 1, b: 2, c: 3 }
Seq(myObject).map(x => x * x).toObject();
// { a: 1, b: 4, c: 9 }
Not that Seq has other properties ("Seq describes a lazy operation, allowing them to efficiently chain use of all the higher-order collection methods (such as map and filter) by not creating intermediate collections") and that some other immutable-js data structures might also do the job quite efficiently.
Anyone using this method will of course have to npm install immutable and might want to read the docs:
https://facebook.github.io/immutable-js/
My response is largely based off the highest rated response here and hopefully everyone understands (have the same explanation on my GitHub, too). This is why his impementation with map works:
Object.keys(images).map((key) => images[key] = 'url(' + '"' + images[key] + '"' +
')');
The purpose of the function is to take an object and modify the original contents of the object using a method available to all objects (objects and arrays alike) without returning an array. Almost everything within JS is an object, and for that reason elements further down the pipeline of inheritance can potentially technically use those available to those up the line (and the reverse it appears).
The reason that this works is due to the .map functions returning an array REQUIRING that you provide an explicit or implicit RETURN of an array instead of simply modifying an existing object. You essentially trick the program into thinking the object is an array by using Object.keys which will allow you to use the map function with its acting on the values the individual keys are associated with (I actually accidentally returned arrays but fixed it). As long as there isn't a return in the normal sense, there will be no array created with the original object stil intact and modified as programmed.
This particular program takes an object called images and takes the values of its keys and appends url tags for use within another function. Original is this:
var images = {
snow: 'https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305',
sunny: 'http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-east-
Matanzas-city- Cuba-20170131-1080.jpg',
rain: 'https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg' };
...and modified is this:
var images = {
snow: url('https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305'),
sunny: url('http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-
east-Matanzas-city- Cuba-20170131-1080.jpg'),
rain: url('https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg')
};
The object's original structure is left intact allowing for normal property access as long as there isn't a return. Do NOT have it return an array like normal and everything will be fine. The goal is REASSIGNING the original values (images[key]) to what is wanted and not anything else. As far as I know, in order to prevent array output there HAS to be REASSIGNMENT of images[key] and no implicit or explicit request to return an array (variable assignment does this and was glitching back and forth for me).
EDIT:
Going to address his other method regarding new object creation to avoid modifying original object (and reassignment appears to still be necessary in order to avoid accidentally creating an array as output). These functions use arrow syntax and are if you simply want to create a new object for future use.
const mapper = (obj, mapFn) => Object.keys(obj).reduce((result, key) => {
result[key] = mapFn(obj)[key];
return result;
}, {});
var newImages = mapper(images, (value) => value);
The way these functions work is like so:
mapFn takes the function to be added later (in this case (value) => value) and simply returns whatever is stored there as a value for that key (or multiplied by two if you change the return value like he did) in mapFn(obj)[key],
and then redefines the original value associated with the key in result[key] = mapFn(obj)[key]
and returns the operation performed on result (the accumulator located in the brackets initiated at the end of the .reduce function).
All of this is being performed on the chosen object and STILL there CANNOT be an implicit request for a returned array and only works when reassigning values as far as I can tell. This requires some mental gymnastics but reduces the lines of code needed as can be seen above. Output is exactly the same as can be seen below:
{snow: "https://www.trbimg.com/img-5aa059f5/turbine/bs-
md-weather-20180305", sunny: "http://www.cubaweather.org/images/weather-
photos/l…morning-east-Matanzas-city-Cuba-20170131-1080.jpg", rain:
"https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg"}
Keep in mind this worked with NON-NUMBERS. You CAN duplicate ANY object by SIMPLY RETURNING THE VALUE in the mapFN function.
const mapObject = (targetObject, callbackFn) => {
if (!targetObject) return targetObject;
if (Array.isArray(targetObject)){
return targetObject.map((v)=>mapObject(v, callbackFn))
}
return Object.entries(targetObject).reduce((acc,[key, value]) => {
const res = callbackFn(key, value);
if (!Array.isArray(res) && typeof res ==='object'){
return {...acc, [key]: mapObject(res, callbackFn)}
}
if (Array.isArray(res)){
return {...acc, [key]: res.map((v)=>mapObject(v, callbackFn))}
}
return {...acc, [key]: res};
},{})
};
const mapped = mapObject(a,(key,value)=> {
if (!Array.isArray(value) && key === 'a') return ;
if (!Array.isArray(value) && key === 'e') return [];
if (!Array.isArray(value) && key === 'g') return value * value;
return value;
});
console.log(JSON.stringify(mapped));
// {"b":2,"c":[{"d":2,"e":[],"f":[{"g":4}]}]}
This function goes recursively through the object and arrays of objects. Attributes can be deleted if returned undefined
I needed a version that allowed modifying the keys as well (based on #Amberlamps and #yonatanmn answers);
var facts = [ // can be an object or array - see jsfiddle below
{uuid:"asdfasdf",color:"red"},
{uuid:"sdfgsdfg",color:"green"},
{uuid:"dfghdfgh",color:"blue"}
];
var factObject = mapObject({}, facts, function(key, item) {
return [item.uuid, {test:item.color, oldKey:key}];
});
function mapObject(empty, obj, mapFunc){
return Object.keys(obj).reduce(function(newObj, key) {
var kvPair = mapFunc(key, obj[key]);
newObj[kvPair[0]] = kvPair[1];
return newObj;
}, empty);
}
factObject=
{
"asdfasdf": {"color":"red","oldKey":"0"},
"sdfgsdfg": {"color":"green","oldKey":"1"},
"dfghdfgh": {"color":"blue","oldKey":"2"}
}
Edit: slight change to pass in the starting object {}. Allows it to be [] (if the keys are integers)
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.prototype.map = function(fn){
var oReturn = {};
for (sCurObjectPropertyName in this) {
oReturn[sCurObjectPropertyName] = fn(this[sCurObjectPropertyName], sCurObjectPropertyName);
}
return oReturn;
}
Object.defineProperty(Object.prototype,'map',{enumerable:false});
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
If anyone was looking for a simple solution that maps an object to a new object or to an array:
// Maps an object to a new object by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObject = (obj, fn) => {
const newObj = {};
Object.keys(obj).forEach(k => { newObj[k] = fn(k, obj[k]); });
return newObj;
};
// Maps an object to a new array by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObjectToArray = (obj, fn) => (
Object.keys(obj).map(k => fn(k, obj[k]))
);
This may not work for all objects or all mapping functions, but it works for plain shallow objects and straightforward mapping functions which is all I needed.
To responds more closely to what precisely the OP asked for, the OP wants an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
to have a map method myObject.map,
similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
The imho best (measured in terms to "close to what is asked" + "no ES{5,6,7} required needlessly") answer would be:
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
The code above avoids intentionally using any language features, only available in recent ECMAScript editions. With the code above the problem can be solved lke this:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
newObject = myObject.map(function (value, label) {
return value * value;
});
console.log("newObject is now",newObject);
alternative test code here
Besides frowned upon by some, it would be a possibility to insert the solution in the prototype chain like this.
Object.prototype.map = function(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property)){
result[property] = callback(this[property],property,this);
}
}
return result;
}
Something, which when done with careful oversight should not have any ill effects and not impact map method of other objects (i.e. Array's map).
First, convert your HTMLCollection using Object.entries(collection). Then it’s an iterable you can now use the .map method on it.
Object.entries(collection).map(...)
reference
https://medium.com/#js_tut/calling-javascript-code-on-multiple-div-elements-without-the-id-attribute-97ff6a50f31
I handle only strings to reduce exemptions:
Object.keys(params).map(k => typeof params[k] == "string" ? params[k] = params[k].trim() : null);
If you're interested in mapping not only values but also keys, I have written Object.map(valueMapper, keyMapper), that behaves this way:
var source = { a: 1, b: 2 };
function sum(x) { return x + x }
source.map(sum); // returns { a: 2, b: 4 }
source.map(undefined, sum); // returns { aa: 1, bb: 2 }
source.map(sum, sum); // returns { aa: 2, bb: 4 }
Hey wrote a little mapper function that might help.
function propertyMapper(object, src){
for (var property in object) {
for (var sourceProp in src) {
if(property === sourceProp){
if(Object.prototype.toString.call( property ) === '[object Array]'){
propertyMapper(object[property], src[sourceProp]);
}else{
object[property] = src[sourceProp];
}
}
}
}
}
A different take on it is to use a custom json stringify function that can also work on deep objects. This might be useful if you intend to post it to the server anyway as json
const obj = { 'a': 1, 'b': 2, x: {'c': 3 }}
const json = JSON.stringify(obj, (k, v) => typeof v === 'number' ? v * v : v)
console.log(json)
console.log('back to json:', JSON.parse(json))
I needed a function to optionally map not only (nor exclusively) values, but also keys. The original object should not change. The object contained only primitive values also.
function mappedObject(obj, keyMapper, valueMapper) {
const mapped = {};
const keys = Object.keys(obj);
const mapKey = typeof keyMapper == 'function';
const mapVal = typeof valueMapper == 'function';
for (let i = 0; i < keys.length; i++) {
const key = mapKey ? keyMapper(keys[i]) : keys[i];
const val = mapVal ? valueMapper(obj[keys[i]]) : obj[keys[i]];
mapped[key] = val;
}
return mapped;
}
Use. Pass a keymapper and a valuemapper function:
const o1 = { x: 1, c: 2 }
mappedObject(o1, k => k + '0', v => v + 1) // {x0: 2, c0: 3}

How to map object values in React? [duplicate]

I have an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
I am looking for a native method, similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
Does JavaScript have such a map function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)
There is no native map to the Object object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
But you could easily iterate over an object using for ... in:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
console.log(myObject);
// { 'a': 2, 'b': 4, 'c': 6 }
Update
A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
// returns a new object with the values at each key mapped using mapFn(value)
function objectMap(object, mapFn) {
return Object.keys(object).reduce(function(result, key) {
result[key] = mapFn(object[key])
return result
}, {})
}
var newObject = objectMap(myObject, function(value) {
return value * 2
})
console.log(newObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }
Array.prototype.reduce reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object {}. On every iteration a new key of myObject is added with twice the key as the value.
Update
With new ES6 features, there is a more elegant way to express objectMap.
const objectMap = (obj, fn) =>
Object.fromEntries(
Object.entries(obj).map(
([k, v], i) => [k, fn(v, k, i)]
)
)
const myObject = { a: 1, b: 2, c: 3 }
console.log(objectMap(myObject, v => 2 * v))
How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries() and Object.fromEntries():
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you can't use Objects.fromEntries, but you can achieve the same using Object.assign in combination with spread operators and computed key names syntax:
let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entries, but you could use Object.keys instead:
let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
array.reduce()
Instead of Object.fromEntries and Object.assign you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
Inherited properties and the prototype chain:
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys() and Object.entries() won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)
No native methods, but lodash#mapValues will do the job brilliantly
_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
// → { 'a': 3, 'b': 6, 'c': 9 }
It's pretty easy to write one:
Object.map = function(o, f, ctx) {
ctx = ctx || this;
var result = {};
Object.keys(o).forEach(function(k) {
result[k] = f.call(ctx, o[k], k, o);
});
return result;
}
with example code:
> o = { a: 1, b: 2, c: 3 };
> r = Object.map(o, function(v, k, o) {
return v * v;
});
> r
{ a : 1, b: 4, c: 9 }
NB: this version also allows you to (optionally) set the this context for the callback, just like the Array method.
EDIT - changed to remove use of Object.prototype, to ensure that it doesn't clash with any existing property named map on the object.
You could use Object.keys and then forEach over the returned array of keys:
var myObject = { 'a': 1, 'b': 2, 'c': 3 },
newObject = {};
Object.keys(myObject).forEach(function (key) {
var value = myObject[key];
newObject[key] = value * value;
});
Or in a more modular fashion:
function map(obj, callback) {
var result = {};
Object.keys(obj).forEach(function (key) {
result[key] = callback.call(obj, obj[key], key, obj);
});
return result;
}
newObject = map(myObject, function(x) { return x * x; });
Note that Object.keys returns an array containing only the object's own enumerable properties, thus it behaves like a for..in loop with a hasOwnProperty check.
This is really annoying, and everyone in the JS community knows it. There should be this functionality:
const obj1 = {a:4, b:7};
const obj2 = Object.map(obj1, (k,v) => v + 5);
console.log(obj1); // {a:4, b:7}
console.log(obj2); // {a:9, b:12}
here is the naïve implementation:
Object.map = function(obj, fn, ctx){
const ret = {};
for(let k of Object.keys(obj)){
ret[k] = fn.call(ctx || null, k, obj[k]);
});
return ret;
};
it is super annoying to have to implement this yourself all the time ;)
If you want something a little more sophisticated, that doesn't interfere with the Object class, try this:
let map = function (obj, fn, ctx) {
return Object.keys(obj).reduce((a, b) => {
a[b] = fn.call(ctx || null, b, obj[b]);
return a;
}, {});
};
const x = map({a: 2, b: 4}, (k,v) => {
return v*2;
});
but it is safe to add this map function to Object, just don't add to Object.prototype.
Object.map = ... // fairly safe
Object.prototype.map ... // not ok
I came here looking to find and answer for mapping an object to an array and got this page as a result. In case you came here looking for the same answer I was, here is how you can map and object to an array.
You can use map to return a new array from the object like so:
var newObject = Object.keys(myObject).map(function(key) {
return myObject[key];
});
Minimal version
ES2017
Object.entries(obj).reduce((a, [k, v]) => (a[k] = v * v, a), {})
↑↑↑↑↑
ES2019
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]))
↑↑↑↑↑
JavaScript just got the new Object.fromEntries method.
Example
function mapObject (obj, fn) {
return Object.fromEntries(
Object
.entries(obj)
.map(fn)
)
}
const myObject = { a: 1, b: 2, c: 3 }
const myNewObject = mapObject(myObject, ([key, value]) => ([key, value * value]))
console.log(myNewObject)
Explanation
The code above converts the Object into an nested Array ([[<key>,<value>], ...]) wich you can map over. Object.fromEntries converts the Array back to an Object.
The cool thing about this pattern, is that you can now easily take object keys into account while mapping.
Documentation
Object.fromEntries()
Object.entries()
Browser Support
Object.fromEntries is currently only supported by these browsers/engines, nevertheless there are polyfills available (e.g #babel/polyfill).
The accepted answer has two drawbacks:
It misuses Array.prototype.reduce, because reducing means to change the structure of a composite type, which doesn't happen in this case.
It is not particularly reusable
An ES6/ES2015 functional approach
Please note that all functions are defined in curried form.
// small, reusable auxiliary functions
const keys = o => Object.keys(o);
const assign = (...o) => Object.assign({}, ...o);
const map = f => xs => xs.map(x => f(x));
const mul = y => x => x * y;
const sqr = x => mul(x) (x);
// the actual map function
const omap = f => o => {
o = assign(o); // A
map(x => o[x] = f(o[x])) (keys(o)); // B
return o;
};
// mock data
const o = {"a":1, "b":2, "c":3};
// and run
console.log(omap(sqr) (o));
console.log(omap(mul(10)) (o));
In line A o is reassigned. Since Javascript passes reference values by sharing, a shallow copy of o is generated. We are now able to mutate o within omap without mutating o in the parent scope.
In line B map's return value is ignored, because map performs a mutation of o. Since this side effect remains within omap and isn't visible in the parent scope, it is totally acceptable.
This is not the fastest solution, but a declarative and reusable one. Here is the same implementation as a one-line, succinct but less readable:
const omap = f => o => (o = assign(o), map(x => o[x] = f(o[x])) (keys(o)), o);
Addendum - why are objects not iterable by default?
ES2015 specified the iterator and iterable protocols. But objects are still not iterable and thus not mappable. The reason is the mixing of data and program level.
For maximum performance.
If your object doesn't change often but needs to be iterated on often I suggest using a native Map as a cache.
// example object
var obj = {a: 1, b: 2, c: 'something'};
// caching map
var objMap = new Map(Object.entries(obj));
// fast iteration on Map object
objMap.forEach((item, key) => {
// do something with an item
console.log(key, item);
});
Object.entries already works in Chrome, Edge, Firefox and beta Opera so it's a future-proof feature.
It's from ES7 so polyfill it https://github.com/es-shims/Object.entries for IE where it doesn't work.
You can convert an object to array simply by using the following:
You can convert the object values to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let valuesArray = Object.values(myObject);
console.log(valuesArray);
You can convert the object keys to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let keysArray = Object.keys(myObject);
console.log(keysArray);
Now you can perform normal array operations, including the 'map' function
you can use map method and forEach on arrays but if you want to use it on Object then you can use it with twist like below:
Using Javascript (ES6)
var obj = { 'a': 2, 'b': 4, 'c': 6 };
Object.entries(obj).map( v => obj[v[0]] *= v[1] );
console.log(obj); //it will log as {a: 4, b: 16, c: 36}
var obj2 = { 'a': 4, 'b': 8, 'c': 10 };
Object.entries(obj2).forEach( v => obj2[v[0]] *= v[1] );
console.log(obj2); //it will log as {a: 16, b: 64, c: 100}
Using jQuery
var ob = { 'a': 2, 'b': 4, 'c': 6 };
$.map(ob, function (val, key) {
ob[key] *= val;
});
console.log(ob) //it will log as {a: 4, b: 16, c: 36}
Or you can use other loops also like $.each method as below example:
$.each(ob,function (key, value) {
ob[key] *= value;
});
console.log(ob) //it will also log as {a: 4, b: 16, c: 36}
The map function does not exist on the Object.prototype however you can emulate it like so
var myMap = function ( obj, callback ) {
var result = {};
for ( var key in obj ) {
if ( Object.prototype.hasOwnProperty.call( obj, key ) ) {
if ( typeof callback === 'function' ) {
result[ key ] = callback.call( obj, obj[ key ], key, obj );
}
}
}
return result;
};
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
var newObject = myMap( myObject, function ( value, key ) {
return value * value;
});
EDIT: The canonical way using newer JavaScript features is -
const identity = x =>
x
const omap = (f = identity, o = {}) =>
Object.fromEntries(
Object.entries(o).map(([ k, v ]) =>
[ k, f(v) ]
)
)
Where o is some object and f is your mapping function. Or we could say, given a function from a -> b, and an object with values of type a, produce an object with values of type b. As a pseudo type signature -
// omap : (a -> b, { a }) -> { b }
The original answer was written to demonstrate a powerful combinator, mapReduce which allows us to think of our transformation in a different way
m, the mapping function – gives you a chance to transform the incoming element before…
r, the reducing function – this function combines the accumulator with the result of the mapped element
Intuitively, mapReduce creates a new reducer we can plug directly into Array.prototype.reduce. But more importantly, we can implement our object functor implementation omap plainly by utilizing the object monoid, Object.assign and {}.
const identity = x =>
x
const mapReduce = (m, r) =>
(a, x) => r (a, m (x))
const omap = (f = identity, o = {}) =>
Object
.keys (o)
.reduce
( mapReduce
( k => ({ [k]: f (o[k]) })
, Object.assign
)
, {}
)
const square = x =>
x * x
const data =
{ a : 1, b : 2, c : 3 }
console .log (omap (square, data))
// { a : 1, b : 4, c : 9 }
Notice the only part of the program we actually had to write is the mapping implementation itself –
k => ({ [k]: f (o[k]) })
Which says, given a known object o and some key k, construct an object and whose computed property k is the result of calling f on the key's value, o[k].
We get a glimpse of mapReduce's sequencing potential if we first abstract oreduce
// oreduce : (string * a -> string * b, b, { a }) -> { b }
const oreduce = (f = identity, r = null, o = {}) =>
Object
.keys (o)
.reduce
( mapReduce
( k => [ k, o[k] ]
, f
)
, r
)
// omap : (a -> b, {a}) -> {b}
const omap = (f = identity, o = {}) =>
oreduce
( mapReduce
( ([ k, v ]) =>
({ [k]: f (v) })
, Object.assign
)
, {}
, o
)
Everything works the same, but omap can be defined at a higher-level now. Of course the new Object.entries makes this look silly, but the exercise is still important to the learner.
You won't see the full potential of mapReduce here, but I share this answer because it's interesting to see just how many places it can be applied. If you're interested in how it is derived and other ways it could be useful, please see this answer.
Object Mapper in TypeScript
I like the examples that use Object.fromEntries such as this one, but still, they are not very easy to use. The answers that use Object.keys and then look up the key are actually doing multiple look-ups that may not be necessary.
I wished there was an Object.map function, but we can create our own and call it objectMap with the ability to modify both key and value:
Usage (JavaScript):
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
// keep the key and modify the value
let obj = objectMap(myObject, val => val * 2);
// obj = { a: 2, b: 4, c: 6 }
// modify both key and value
obj = objectMap(myObject,
val => val * 2 + '',
key => (key + key).toUpperCase());
// obj = { AA: '2', BB: '4', CC: '6' }
Code (TypeScript):
interface Dictionary<T> {
[key: string]: T;
}
function objectMap<TValue, TResult>(
obj: Dictionary<TValue>,
valSelector: (val: TValue, obj: Dictionary<TValue>) => TResult,
keySelector?: (key: string, obj: Dictionary<TValue>) => string,
ctx?: Dictionary<TValue>
) {
const ret = {} as Dictionary<TResult>;
for (const key of Object.keys(obj)) {
const retKey = keySelector
? keySelector.call(ctx || null, key, obj)
: key;
const retVal = valSelector.call(ctx || null, obj[key], obj);
ret[retKey] = retVal;
}
return ret;
}
If you are not using TypeScript then copy the above code in TypeScript Playground to get the JavaScript code.
Also, the reason I put keySelector after valSelector in the parameter list, is because it is optional.
* Some credit go to alexander-mills' answer.
Based on #Amberlamps answer, here's a utility function
(as a comment it looked ugly)
function mapObject(obj, mapFunc){
return Object.keys(obj).reduce(function(newObj, value) {
newObj[value] = mapFunc(obj[value]);
return newObj;
}, {});
}
and the use is:
var obj = {a:1, b:3, c:5}
function double(x){return x * 2}
var newObj = mapObject(obj, double);
//=> {a: 2, b: 6, c: 10}
I came upon this as a first-item in a Google search trying to learn to do this, and thought I would share for other folsk finding this recently the solution I found, which uses the npm package immutable.
I think its interesting to share because immutable uses the OP's EXACT situation in their own documentation - the following is not my own code but pulled from the current immutable-js documentation:
const { Seq } = require('immutable')
const myObject = { a: 1, b: 2, c: 3 }
Seq(myObject).map(x => x * x).toObject();
// { a: 1, b: 4, c: 9 }
Not that Seq has other properties ("Seq describes a lazy operation, allowing them to efficiently chain use of all the higher-order collection methods (such as map and filter) by not creating intermediate collections") and that some other immutable-js data structures might also do the job quite efficiently.
Anyone using this method will of course have to npm install immutable and might want to read the docs:
https://facebook.github.io/immutable-js/
My response is largely based off the highest rated response here and hopefully everyone understands (have the same explanation on my GitHub, too). This is why his impementation with map works:
Object.keys(images).map((key) => images[key] = 'url(' + '"' + images[key] + '"' +
')');
The purpose of the function is to take an object and modify the original contents of the object using a method available to all objects (objects and arrays alike) without returning an array. Almost everything within JS is an object, and for that reason elements further down the pipeline of inheritance can potentially technically use those available to those up the line (and the reverse it appears).
The reason that this works is due to the .map functions returning an array REQUIRING that you provide an explicit or implicit RETURN of an array instead of simply modifying an existing object. You essentially trick the program into thinking the object is an array by using Object.keys which will allow you to use the map function with its acting on the values the individual keys are associated with (I actually accidentally returned arrays but fixed it). As long as there isn't a return in the normal sense, there will be no array created with the original object stil intact and modified as programmed.
This particular program takes an object called images and takes the values of its keys and appends url tags for use within another function. Original is this:
var images = {
snow: 'https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305',
sunny: 'http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-east-
Matanzas-city- Cuba-20170131-1080.jpg',
rain: 'https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg' };
...and modified is this:
var images = {
snow: url('https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305'),
sunny: url('http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-
east-Matanzas-city- Cuba-20170131-1080.jpg'),
rain: url('https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg')
};
The object's original structure is left intact allowing for normal property access as long as there isn't a return. Do NOT have it return an array like normal and everything will be fine. The goal is REASSIGNING the original values (images[key]) to what is wanted and not anything else. As far as I know, in order to prevent array output there HAS to be REASSIGNMENT of images[key] and no implicit or explicit request to return an array (variable assignment does this and was glitching back and forth for me).
EDIT:
Going to address his other method regarding new object creation to avoid modifying original object (and reassignment appears to still be necessary in order to avoid accidentally creating an array as output). These functions use arrow syntax and are if you simply want to create a new object for future use.
const mapper = (obj, mapFn) => Object.keys(obj).reduce((result, key) => {
result[key] = mapFn(obj)[key];
return result;
}, {});
var newImages = mapper(images, (value) => value);
The way these functions work is like so:
mapFn takes the function to be added later (in this case (value) => value) and simply returns whatever is stored there as a value for that key (or multiplied by two if you change the return value like he did) in mapFn(obj)[key],
and then redefines the original value associated with the key in result[key] = mapFn(obj)[key]
and returns the operation performed on result (the accumulator located in the brackets initiated at the end of the .reduce function).
All of this is being performed on the chosen object and STILL there CANNOT be an implicit request for a returned array and only works when reassigning values as far as I can tell. This requires some mental gymnastics but reduces the lines of code needed as can be seen above. Output is exactly the same as can be seen below:
{snow: "https://www.trbimg.com/img-5aa059f5/turbine/bs-
md-weather-20180305", sunny: "http://www.cubaweather.org/images/weather-
photos/l…morning-east-Matanzas-city-Cuba-20170131-1080.jpg", rain:
"https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg"}
Keep in mind this worked with NON-NUMBERS. You CAN duplicate ANY object by SIMPLY RETURNING THE VALUE in the mapFN function.
const mapObject = (targetObject, callbackFn) => {
if (!targetObject) return targetObject;
if (Array.isArray(targetObject)){
return targetObject.map((v)=>mapObject(v, callbackFn))
}
return Object.entries(targetObject).reduce((acc,[key, value]) => {
const res = callbackFn(key, value);
if (!Array.isArray(res) && typeof res ==='object'){
return {...acc, [key]: mapObject(res, callbackFn)}
}
if (Array.isArray(res)){
return {...acc, [key]: res.map((v)=>mapObject(v, callbackFn))}
}
return {...acc, [key]: res};
},{})
};
const mapped = mapObject(a,(key,value)=> {
if (!Array.isArray(value) && key === 'a') return ;
if (!Array.isArray(value) && key === 'e') return [];
if (!Array.isArray(value) && key === 'g') return value * value;
return value;
});
console.log(JSON.stringify(mapped));
// {"b":2,"c":[{"d":2,"e":[],"f":[{"g":4}]}]}
This function goes recursively through the object and arrays of objects. Attributes can be deleted if returned undefined
I needed a version that allowed modifying the keys as well (based on #Amberlamps and #yonatanmn answers);
var facts = [ // can be an object or array - see jsfiddle below
{uuid:"asdfasdf",color:"red"},
{uuid:"sdfgsdfg",color:"green"},
{uuid:"dfghdfgh",color:"blue"}
];
var factObject = mapObject({}, facts, function(key, item) {
return [item.uuid, {test:item.color, oldKey:key}];
});
function mapObject(empty, obj, mapFunc){
return Object.keys(obj).reduce(function(newObj, key) {
var kvPair = mapFunc(key, obj[key]);
newObj[kvPair[0]] = kvPair[1];
return newObj;
}, empty);
}
factObject=
{
"asdfasdf": {"color":"red","oldKey":"0"},
"sdfgsdfg": {"color":"green","oldKey":"1"},
"dfghdfgh": {"color":"blue","oldKey":"2"}
}
Edit: slight change to pass in the starting object {}. Allows it to be [] (if the keys are integers)
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.prototype.map = function(fn){
var oReturn = {};
for (sCurObjectPropertyName in this) {
oReturn[sCurObjectPropertyName] = fn(this[sCurObjectPropertyName], sCurObjectPropertyName);
}
return oReturn;
}
Object.defineProperty(Object.prototype,'map',{enumerable:false});
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
If anyone was looking for a simple solution that maps an object to a new object or to an array:
// Maps an object to a new object by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObject = (obj, fn) => {
const newObj = {};
Object.keys(obj).forEach(k => { newObj[k] = fn(k, obj[k]); });
return newObj;
};
// Maps an object to a new array by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObjectToArray = (obj, fn) => (
Object.keys(obj).map(k => fn(k, obj[k]))
);
This may not work for all objects or all mapping functions, but it works for plain shallow objects and straightforward mapping functions which is all I needed.
To responds more closely to what precisely the OP asked for, the OP wants an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
to have a map method myObject.map,
similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
The imho best (measured in terms to "close to what is asked" + "no ES{5,6,7} required needlessly") answer would be:
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
The code above avoids intentionally using any language features, only available in recent ECMAScript editions. With the code above the problem can be solved lke this:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
newObject = myObject.map(function (value, label) {
return value * value;
});
console.log("newObject is now",newObject);
alternative test code here
Besides frowned upon by some, it would be a possibility to insert the solution in the prototype chain like this.
Object.prototype.map = function(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property)){
result[property] = callback(this[property],property,this);
}
}
return result;
}
Something, which when done with careful oversight should not have any ill effects and not impact map method of other objects (i.e. Array's map).
First, convert your HTMLCollection using Object.entries(collection). Then it’s an iterable you can now use the .map method on it.
Object.entries(collection).map(...)
reference
https://medium.com/#js_tut/calling-javascript-code-on-multiple-div-elements-without-the-id-attribute-97ff6a50f31
I handle only strings to reduce exemptions:
Object.keys(params).map(k => typeof params[k] == "string" ? params[k] = params[k].trim() : null);
If you're interested in mapping not only values but also keys, I have written Object.map(valueMapper, keyMapper), that behaves this way:
var source = { a: 1, b: 2 };
function sum(x) { return x + x }
source.map(sum); // returns { a: 2, b: 4 }
source.map(undefined, sum); // returns { aa: 1, bb: 2 }
source.map(sum, sum); // returns { aa: 2, bb: 4 }
Hey wrote a little mapper function that might help.
function propertyMapper(object, src){
for (var property in object) {
for (var sourceProp in src) {
if(property === sourceProp){
if(Object.prototype.toString.call( property ) === '[object Array]'){
propertyMapper(object[property], src[sourceProp]);
}else{
object[property] = src[sourceProp];
}
}
}
}
}
A different take on it is to use a custom json stringify function that can also work on deep objects. This might be useful if you intend to post it to the server anyway as json
const obj = { 'a': 1, 'b': 2, x: {'c': 3 }}
const json = JSON.stringify(obj, (k, v) => typeof v === 'number' ? v * v : v)
console.log(json)
console.log('back to json:', JSON.parse(json))
I needed a function to optionally map not only (nor exclusively) values, but also keys. The original object should not change. The object contained only primitive values also.
function mappedObject(obj, keyMapper, valueMapper) {
const mapped = {};
const keys = Object.keys(obj);
const mapKey = typeof keyMapper == 'function';
const mapVal = typeof valueMapper == 'function';
for (let i = 0; i < keys.length; i++) {
const key = mapKey ? keyMapper(keys[i]) : keys[i];
const val = mapVal ? valueMapper(obj[keys[i]]) : obj[keys[i]];
mapped[key] = val;
}
return mapped;
}
Use. Pass a keymapper and a valuemapper function:
const o1 = { x: 1, c: 2 }
mappedObject(o1, k => k + '0', v => v + 1) // {x0: 2, c0: 3}

How to name object keys on a loop in es6 [duplicate]

I need to sort JavaScript objects by key.
Hence the following:
{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
Would become:
{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.
See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:
All methods that iterate over property keys do so in the same order:
First all Array indices, sorted numerically.
Then all string keys (that are not indices), in the order in which they were created.
Then all symbols, in the order in which they were created.
So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.
Here’s how you can sort an object by its keys/properties, alphabetically:
const unordered = {
'b': 'foo',
'c': 'bar',
'a': 'baz'
};
console.log(JSON.stringify(unordered));
// → '{"b":"foo","c":"bar","a":"baz"}'
const ordered = Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
console.log(JSON.stringify(ordered));
// → '{"a":"baz","b":"foo","c":"bar"}'
Use var instead of const for compatibility with ES5 engines.
JavaScript objects1 are not ordered. It is meaningless to try to "sort" them. If you want to iterate over an object's properties, you can sort the keys and then retrieve the associated values:
var myObj = {
'b': 'asdsadfd',
'c': 'masdasaf',
'a': 'dsfdsfsdf'
},
keys = [],
k, i, len;
for (k in myObj) {
if (myObj.hasOwnProperty(k)) {
keys.push(k);
}
}
keys.sort();
len = keys.length;
for (i = 0; i < len; i++) {
k = keys[i];
console.log(k + ':' + myObj[k]);
}
Alternate implementation using Object.keys fanciness:
var myObj = {
'b': 'asdsadfd',
'c': 'masdasaf',
'a': 'dsfdsfsdf'
},
keys = Object.keys(myObj),
i, len = keys.length;
keys.sort();
for (i = 0; i < len; i++) {
k = keys[i];
console.log(k + ':' + myObj[k]);
}
1Not to be pedantic, but there's no such thing as a JSON object.
A lot of people have mention that "objects cannot be sorted", but after that they are giving you a solution which works. Paradox, isn't it?
No one mention why those solutions are working. They are, because in most of the browser's implementations values in objects are stored in the order in which they were added. That's why if you create new object from sorted list of keys it's returning an expected result.
And I think that we could add one more solution – ES5 functional way:
function sortObject(obj) {
return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
}
ES2015 version of above (formatted to "one-liner"):
const sortObject = o => Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {})
Short explanation of above examples (as asked in comments):
Object.keys is giving us a list of keys in provided object (obj or o), then we're sorting those using default sorting algorithm, next .reduce is used to convert that array back into an object, but this time with all of the keys sorted.
Guys I'm figuratively shocked! Sure all answers are somewhat old, but no one did even mention the stability in sorting! So bear with me I'll try my best to answer the question itself and go into details here. So I'm going to apologize now it will be a lot to read.
Since it is 2018 I will only use ES6, the Polyfills are all available at the MDN docs, which I will link at the given part.
Answer to the question:
If your keys are only numbers then you can safely use Object.keys() together with Array.prototype.reduce() to return the sorted object:
// Only numbers to show it will be sorted.
const testObj = {
'2000': 'Articel1',
'4000': 'Articel2',
'1000': 'Articel3',
'3000': 'Articel4',
};
// I'll explain what reduces does after the answer.
console.log(Object.keys(testObj).reduce((accumulator, currentValue) => {
accumulator[currentValue] = testObj[currentValue];
return accumulator;
}, {}));
/**
* expected output:
* {
* '1000': 'Articel3',
* '2000': 'Articel1',
* '3000': 'Articel4',
* '4000': 'Articel2'
* }
*/
// if needed here is the one liner:
console.log(Object.keys(testObj).reduce((a, c) => (a[c] = testObj[c], a), {}));
However if you are working with strings I highly recommend chaining Array.prototype.sort() into all of this:
// String example
const testObj = {
'a1d78eg8fdg387fg38': 'Articel1',
'z12989dh89h31d9h39': 'Articel2',
'f1203391dhj32189h2': 'Articel3',
'b10939hd83f9032003': 'Articel4',
};
// Chained sort into all of this.
console.log(Object.keys(testObj).sort().reduce((accumulator, currentValue) => {
accumulator[currentValue] = testObj[currentValue];
return accumulator;
}, {}));
/**
* expected output:
* {
* a1d78eg8fdg387fg38: 'Articel1',
* b10939hd83f9032003: 'Articel4',
* f1203391dhj32189h2: 'Articel3',
* z12989dh89h31d9h39: 'Articel2'
* }
*/
// again the one liner:
console.log(Object.keys(testObj).sort().reduce((a, c) => (a[c] = testObj[c], a), {}));
If someone is wondering what reduce does:
// Will return Keys of object as an array (sorted if only numbers or single strings like a,b,c).
Object.keys(testObj)
// Chaining reduce to the returned array from Object.keys().
// Array.prototype.reduce() takes one callback
// (and another param look at the last line) and passes 4 arguments to it:
// accumulator, currentValue, currentIndex and array
.reduce((accumulator, currentValue) => {
// setting the accumulator (sorted new object) with the actual property from old (unsorted) object.
accumulator[currentValue] = testObj[currentValue];
// returning the newly sorted object for the next element in array.
return accumulator;
// the empty object {} ist the initial value for Array.prototype.reduce().
}, {});
If needed here is the explanation for the one liner:
Object.keys(testObj).reduce(
// Arrow function as callback parameter.
(a, c) =>
// parenthesis return! so we can safe the return and write only (..., a);
(a[c] = testObj[c], a)
// initial value for reduce.
,{}
);
Docs for reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Why use parenthesis on JavaScript return statements: http://jamesknelson.com/javascript-return-parenthesis/
Why Sorting is a bit complicated:
In short Object.keys() will return an array with the same order as we get with a normal loop:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
Object.keys() returns an array whose elements are strings
corresponding to the enumerable properties found directly upon object.
The ordering of the properties is the same as that given by looping
over the properties of the object manually.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Sidenote - you can use Object.keys() on arrays as well, keep in mind the index will be returned:
// simple array
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
But it is not as easy as shown by those examples, real world objects may contain numbers and alphabetical characters or even symbols (please don't do it).
Here is an example with all of them in one object:
// This is just to show what happens, please don't use symbols in keys.
const testObj = {
'1asc': '4444',
1000: 'a',
b: '1231',
'#01010101010': 'asd',
2: 'c'
};
console.log(Object.keys(testObj));
// output: [ '2', '1000', '1asc', 'b', '#01010101010' ]
Now if we use Array.prototype.sort() on the array above the output changes:
console.log(Object.keys(testObj).sort());
// output: [ '#01010101010', '1000', '1asc', '2', 'b' ]
Here is a quote from the docs:
The sort() method sorts the elements of an array in place and returns
the array. The sort is not necessarily stable. The default sort order
is according to string Unicode code points.
The time and space complexity of the sort cannot be guaranteed as it
is implementation dependent.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You have to make sure that one of them returns the desired output for you. In reallife examples people tend to mix up things expecially if you use different information inputs like APIs and Databases together.
So what's the big deal?
Well there are two articles which every programmer should understand:
In-place algorithm:
In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. In-place algorithm updates input sequence only through replacement or swapping of elements. An algorithm which is not in-place is sometimes called not-in-place or out-of-place.
So basically our old array will be overwritten! This is important if you want to keep the old array for other reasons. So keep this in mind.
Sorting algorithm
Stable sort algorithms sort identical elements in the same order that
they appear in the input. When sorting some kinds of data, only part
of the data is examined when determining the sort order. For example,
in the card sorting example to the right, the cards are being sorted
by their rank, and their suit is being ignored. This allows the
possibility of multiple different correctly sorted versions of the
original list. Stable sorting algorithms choose one of these,
according to the following rule: if two items compare as equal, like
the two 5 cards, then their relative order will be preserved, so that
if one came before the other in the input, it will also come before
the other in the output.
An example of stable sort on playing cards. When the cards are sorted
by rank with a stable sort, the two 5s must remain in the same order
in the sorted output that they were originally in. When they are
sorted with a non-stable sort, the 5s may end up in the opposite order
in the sorted output.
This shows that the sorting is right but it changed. So in the real world even if the sorting is correct we have to make sure that we get what we expect! This is super important keep this in mind as well. For more JavaScript examples look into the Array.prototype.sort() - docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
It's 2019 and we have a 2019 way to solve this :)
Object.fromEntries(Object.entries({b: 3, a:8, c:1}).sort())
ES6 - here is the 1 liner
var data = { zIndex:99,
name:'sravan',
age:25,
position:'architect',
amount:'100k',
manager:'mammu' };
console.log(Object.entries(data).sort().reduce( (o,[k,v]) => (o[k]=v,o), {} ));
This works for me
/**
* Return an Object sorted by it's Key
*/
var sortObjectByKey = function(obj){
var keys = [];
var sorted_obj = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
keys.push(key);
}
}
// sort keys
keys.sort();
// create new array based on Sorted Keys
jQuery.each(keys, function(i, key){
sorted_obj[key] = obj[key];
});
return sorted_obj;
};
This is an old question, but taking the cue from Mathias Bynens' answer, I've made a short version to sort the current object, without much overhead.
Object.keys(unordered).sort().forEach(function(key) {
var value = unordered[key];
delete unordered[key];
unordered[key] = value;
});
after the code execution, the "unordered" object itself will have the keys alphabetically sorted.
Using lodash this will work:
some_map = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
// perform a function in order of ascending key
_(some_map).keys().sort().each(function (key) {
var value = some_map[key];
// do something
});
// or alternatively to build a sorted list
sorted_list = _(some_map).keys().sort().map(function (key) {
var value = some_map[key];
// return something that shall become an item in the sorted list
}).value();
Just food for thought.
Suppose it could be useful in VisualStudio debugger which shows unordered object properties.
(function(s) {
var t = {};
Object.keys(s).sort().forEach(function(k) {
t[k] = s[k]
});
return t
})({
b: 2,
a: 1,
c: 3
});
The same as inline version:
(function(s){var t={};Object.keys(s).sort().forEach(function(k){t[k]=s[k]});return t})({b:2,a:1,c:3})
I am actually very surprised that over 30 answers were given, and yet none gave a full deep solution for this problem. Some had shallow solution, while others had deep but faulty (it'll crash if undefined, function or symbol will be in the json).
Here is the full solution:
function sortObject(unordered, sortArrays = false) {
if (!unordered || typeof unordered !== 'object') {
return unordered;
}
if (Array.isArray(unordered)) {
const newArr = unordered.map((item) => sortObject(item, sortArrays));
if (sortArrays) {
newArr.sort();
}
return newArr;
}
const ordered = {};
Object.keys(unordered)
.sort()
.forEach((key) => {
ordered[key] = sortObject(unordered[key], sortArrays);
});
return ordered;
}
const json = {
b: 5,
a: [2, 1],
d: {
b: undefined,
a: null,
c: false,
d: true,
g: '1',
f: [],
h: {},
i: 1n,
j: () => {},
k: Symbol('a')
},
c: [
{
b: 1,
a: 1
}
]
};
console.log(sortObject(json, true));
Underscore version:
function order(unordered)
{
return _.object(_.sortBy(_.pairs(unordered),function(o){return o[0]}));
}
If you don't trust your browser for keeping the order of the keys, I strongly suggest to rely on a ordered array of key-value paired arrays.
_.sortBy(_.pairs(c),function(o){return o[0]})
function sortObjectKeys(obj){
return Object.keys(obj).sort().reduce((acc,key)=>{
acc[key]=obj[key];
return acc;
},{});
}
sortObjectKeys({
telephone: '069911234124',
name: 'Lola',
access: true,
});
Maybe a bit more elegant form:
/**
* Sorts a key-value object by key, maintaining key to data correlations.
* #param {Object} src key-value object
* #returns {Object}
*/
var ksort = function ( src ) {
var keys = Object.keys( src ),
target = {};
keys.sort();
keys.forEach(function ( key ) {
target[ key ] = src[ key ];
});
return target;
};
// Usage
console.log(ksort({
a:1,
c:3,
b:2
}));
P.S. and the same with ES6+ syntax:
function ksort( src ) {
const keys = Object.keys( src );
keys.sort();
return keys.reduce(( target, key ) => {
target[ key ] = src[ key ];
return target;
}, {});
};
Here is a one line solution (not the most efficient but when it comes to thin objects like in your example I'd rather use native JS functions then messing up with sloppy loops)
const unordered = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
const ordered = Object.fromEntries(Object.entries(unordered).sort())
console.log(ordered); // a->b->c
// if keys are char/string
const sortObject = (obj) => Object.fromEntries(Object.entries(obj).sort( ));
let obj = { c: 3, a: 1 };
obj = sortObject(obj)
// if keys are numbers
const sortObject = (obj) => Object.fromEntries(Object.entries(obj).sort( (a,b)=>a-b ));
let obj = { 3: 'c', 1: 'a' };
obj = sortObject(obj)
const sortObjectByKeys = (object, asc = true) => Object.fromEntries(
Object.entries(object).sort(([k1], [k2]) => k1 < k2 ^ !asc ? -1 : 1),
)
const object = { b: 'asdsad', c: 'masdas', a: 'dsfdsfsdf' }
const orderedObject = sortObjectByKeys(object)
console.log(orderedObject)
recursive sort, for nested object and arrays
function sortObjectKeys(obj){
return Object.keys(obj).sort().reduce((acc,key)=>{
if (Array.isArray(obj[key])){
acc[key]=obj[key].map(sortObjectKeys);
}
if (typeof obj[key] === 'object'){
acc[key]=sortObjectKeys(obj[key]);
}
else{
acc[key]=obj[key];
}
return acc;
},{});
}
// test it
sortObjectKeys({
telephone: '069911234124',
name: 'Lola',
access: true,
cars: [
{name: 'Family', brand: 'Volvo', cc:1600},
{
name: 'City', brand: 'VW', cc:1200,
interior: {
wheel: 'plastic',
radio: 'blaupunkt'
}
},
{
cc:2600, name: 'Killer', brand: 'Plymouth',
interior: {
wheel: 'wooden',
radio: 'earache!'
}
},
]
});
Here is a clean lodash-based version that works with nested objects
/**
* Sort of the keys of an object alphabetically
*/
const sortKeys = function(obj) {
if(_.isArray(obj)) {
return obj.map(sortKeys);
}
if(_.isObject(obj)) {
return _.fromPairs(_.keys(obj).sort().map(key => [key, sortKeys(obj[key])]));
}
return obj;
};
It would be even cleaner if lodash had a toObject() method...
There's a great project by #sindresorhus called sort-keys that works awesome.
You can check its source code here:
https://github.com/sindresorhus/sort-keys
Or you can use it with npm:
$ npm install --save sort-keys
Here are also code examples from his readme
const sortKeys = require('sort-keys');
sortKeys({c: 0, a: 0, b: 0});
//=> {a: 0, b: 0, c: 0}
sortKeys({b: {b: 0, a: 0}, a: 0}, {deep: true});
//=> {a: 0, b: {a: 0, b: 0}}
sortKeys({c: 0, a: 0, b: 0}, {
compare: (a, b) => -a.localeCompare(b)
});
//=> {c: 0, b: 0, a: 0}
Object.keys(unordered).sort().reduce(
(acc,curr) => ({...acc, [curr]:unordered[curr]})
, {}
)
Use this code if you have nested objects or if you have nested array obj.
var sortObjectByKey = function(obj){
var keys = [];
var sorted_obj = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
keys.push(key);
}
}
// sort keys
keys.sort();
// create new array based on Sorted Keys
jQuery.each(keys, function(i, key){
var val = obj[key];
if(val instanceof Array){
//do for loop;
var arr = [];
jQuery.each(val,function(){
arr.push(sortObjectByKey(this));
});
val = arr;
}else if(val instanceof Object){
val = sortObjectByKey(val)
}
sorted_obj[key] = val;
});
return sorted_obj;
};
As already mentioned, objects are unordered.
However...
You may find this idiom useful:
var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };
var kv = [];
for (var k in o) {
kv.push([k, o[k]]);
}
kv.sort()
You can then iterate through kv and do whatever you wish.
> kv.sort()
[ [ 'a', 'dsfdsfsdf' ],
[ 'b', 'asdsad' ],
[ 'c', 'masdas' ] ]
Just use lodash to unzip map and sortBy first value of pair and zip again it will return sorted key.
If you want sortby value change pair index to 1 instead of 0
var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };
console.log(_(o).toPairs().sortBy(0).fromPairs().value())
Sorts keys recursively while preserving references.
function sortKeys(o){
if(o && o.constructor === Array)
o.forEach(i=>sortKeys(i));
else if(o && o.constructor === Object)
Object.entries(o).sort((a,b)=>a[0]>b[0]?1:-1).forEach(e=>{
sortKeys(e[1]);
delete o[e[0]];
o[e[0]] = e[1];
});
}
Example:
let x = {d:3, c:{g:20, a:[3,2,{s:200, a:100}]}, a:1};
let y = x.c;
let z = x.c.a[2];
sortKeys(x);
console.log(x); // {a: 1, c: {a: [3, 2, {a: 1, s: 2}], g: 2}, d: 3}
console.log(y); // {a: [3, 2, {a: 100, s: 200}}, g: 20}
console.log(z); // {a: 100, s: 200}
This is a lightweight solution to everything I need for JSON sorting.
function sortObj(obj) {
if (typeof obj !== "object" || obj === null)
return obj;
if (Array.isArray(obj))
return obj.map((e) => sortObj(e)).sort();
return Object.keys(obj).sort().reduce((sorted, k) => {
sorted[k] = sortObj(obj[k]);
return sorted;
}, {});
}
Solution:
function getSortedObject(object) {
var sortedObject = {};
var keys = Object.keys(object);
keys.sort();
for (var i = 0, size = keys.length; i < size; i++) {
key = keys[i];
value = object[key];
sortedObject[key] = value;
}
return sortedObject;
}
// Test run
getSortedObject({d: 4, a: 1, b: 2, c: 3});
Explanation:
Many JavaScript runtimes store values inside an object in the order in which they are added.
To sort the properties of an object by their keys you can make use of the Object.keys function which will return an array of keys. The array of keys can then be sorted by the Array.prototype.sort() method which sorts the elements of an array in place (no need to assign them to a new variable).
Once the keys are sorted you can start using them one-by-one to access the contents of the old object to fill a new object (which is now sorted).
Below is an example of the procedure (you can test it in your targeted browsers):
/**
* Returns a copy of an object, which is ordered by the keys of the original object.
*
* #param {Object} object - The original object.
* #returns {Object} Copy of the original object sorted by keys.
*/
function getSortedObject(object) {
// New object which will be returned with sorted keys
var sortedObject = {};
// Get array of keys from the old/current object
var keys = Object.keys(object);
// Sort keys (in place)
keys.sort();
// Use sorted keys to copy values from old object to the new one
for (var i = 0, size = keys.length; i < size; i++) {
key = keys[i];
value = object[key];
sortedObject[key] = value;
}
// Return the new object
return sortedObject;
}
/**
* Test run
*/
var unsortedObject = {
d: 4,
a: 1,
b: 2,
c: 3
};
var sortedObject = getSortedObject(unsortedObject);
for (var key in sortedObject) {
var text = "Key: " + key + ", Value: " + sortedObject[key];
var paragraph = document.createElement('p');
paragraph.textContent = text;
document.body.appendChild(paragraph);
}
Note: Object.keys is an ECMAScript 5.1 method but here is a polyfill for older browsers:
if (!Object.keys) {
Object.keys = function (object) {
var key = [];
var property = undefined;
for (property in object) {
if (Object.prototype.hasOwnProperty.call(object, property)) {
key.push(property);
}
}
return key;
};
}
I transfered some Java enums to javascript objects.
These objects returned correct arrays for me. if object keys are mixed type (string, int, char), there is a problem.
var Helper = {
isEmpty: function (obj) {
return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;
},
isObject: function (obj) {
return (typeof obj === 'object');
},
sortObjectKeys: function (object) {
return Object.keys(object)
.sort(function (a, b) {
c = a - b;
return c
});
},
containsItem: function (arr, item) {
if (arr && Array.isArray(arr)) {
return arr.indexOf(item) > -1;
} else {
return arr === item;
}
},
pushArray: function (arr1, arr2) {
if (arr1 && arr2 && Array.isArray(arr1)) {
arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);
}
}
};
function TypeHelper() {
var _types = arguments[0],
_defTypeIndex = 0,
_currentType,
_value;
if (arguments.length == 2) {
_defTypeIndex = arguments[1];
}
Object.defineProperties(this, {
Key: {
get: function () {
return _currentType;
},
set: function (val) {
_currentType.setType(val, true);
},
enumerable: true
},
Value: {
get: function () {
return _types[_currentType];
},
set: function (val) {
_value.setType(val, false);
},
enumerable: true
}
});
this.getAsList = function (keys) {
var list = [];
Helper.sortObjectKeys(_types).forEach(function (key, idx, array) {
if (key && _types[key]) {
if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {
var json = {};
json.Key = key;
json.Value = _types[key];
Helper.pushArray(list, json);
}
}
});
return list;
};
this.setType = function (value, isKey) {
if (!Helper.isEmpty(value)) {
Object.keys(_types).forEach(function (key, idx, array) {
if (Helper.isObject(value)) {
if (value && value.Key == key) {
_currentType = key;
}
} else if (isKey) {
if (value && value.toString() == key.toString()) {
_currentType = key;
}
} else if (value && value.toString() == _types[key]) {
_currentType = key;
}
});
} else {
this.setDefaultType();
}
return isKey ? _types[_currentType] : _currentType;
};
this.setTypeByIndex = function (index) {
var keys = Helper.sortObjectKeys(_types);
for (var i = 0; i < keys.length; i++) {
if (index === i) {
_currentType = keys[index];
break;
}
}
};
this.setDefaultType = function () {
this.setTypeByIndex(_defTypeIndex);
};
this.setDefaultType();
}
var TypeA = {
"-1": "Any",
"2": "2L",
"100": "100L",
"200": "200L",
"1000": "1000L"
};
var TypeB = {
"U": "Any",
"W": "1L",
"V": "2L",
"A": "100L",
"Z": "200L",
"K": "1000L"
};
console.log('keys of TypeA', Helper.sortObjectKeys(TypeA));//keys of TypeA ["-1", "2", "100", "200", "1000"]
console.log('keys of TypeB', Helper.sortObjectKeys(TypeB));//keys of TypeB ["U", "W", "V", "A", "Z", "K"]
var objectTypeA = new TypeHelper(TypeA),
objectTypeB = new TypeHelper(TypeB);
console.log('list of objectA = ', objectTypeA.getAsList());
console.log('list of objectB = ', objectTypeB.getAsList());
Types:
var TypeA = {
"-1": "Any",
"2": "2L",
"100": "100L",
"200": "200L",
"1000": "1000L"
};
var TypeB = {
"U": "Any",
"W": "1L",
"V": "2L",
"A": "100L",
"Z": "200L",
"K": "1000L"
};
Sorted Keys(output):
Key list of TypeA -> ["-1", "2", "100", "200", "1000"]
Key list of TypeB -> ["U", "W", "V", "A", "Z", "K"]
The one line:
Object.entries(unordered)
.sort(([keyA], [keyB]) => keyA > keyB)
.reduce((obj, [key,value]) => Object.assign(obj, {[key]: value}), {})
Pure JavaScript answer to sort an Object. This is the only answer that I know of that will handle negative numbers. This function is for sorting numerical Objects.
Input
obj = {1000: {}, -1200: {}, 10000: {}, 200: {}};
function osort(obj) {
var keys = Object.keys(obj);
var len = keys.length;
var rObj = [];
var rK = [];
var t = Object.keys(obj).length;
while(t > rK.length) {
var l = null;
for(var x in keys) {
if(l && parseInt(keys[x]) < parseInt(l)) {
l = keys[x];
k = x;
}
if(!l) { // Find Lowest
var l = keys[x];
var k = x;
}
}
delete keys[k];
rK.push(l);
}
for (var i = 0; i < len; i++) {
k = rK[i];
rObj.push(obj[k]);
}
return rObj;
}
The output will be an object sorted by those numbers with new keys starting at 0.

How to properly order the results of an object in Javascript [duplicate]

I need to sort JavaScript objects by key.
Hence the following:
{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
Would become:
{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.
See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:
All methods that iterate over property keys do so in the same order:
First all Array indices, sorted numerically.
Then all string keys (that are not indices), in the order in which they were created.
Then all symbols, in the order in which they were created.
So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.
Here’s how you can sort an object by its keys/properties, alphabetically:
const unordered = {
'b': 'foo',
'c': 'bar',
'a': 'baz'
};
console.log(JSON.stringify(unordered));
// → '{"b":"foo","c":"bar","a":"baz"}'
const ordered = Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
console.log(JSON.stringify(ordered));
// → '{"a":"baz","b":"foo","c":"bar"}'
Use var instead of const for compatibility with ES5 engines.
JavaScript objects1 are not ordered. It is meaningless to try to "sort" them. If you want to iterate over an object's properties, you can sort the keys and then retrieve the associated values:
var myObj = {
'b': 'asdsadfd',
'c': 'masdasaf',
'a': 'dsfdsfsdf'
},
keys = [],
k, i, len;
for (k in myObj) {
if (myObj.hasOwnProperty(k)) {
keys.push(k);
}
}
keys.sort();
len = keys.length;
for (i = 0; i < len; i++) {
k = keys[i];
console.log(k + ':' + myObj[k]);
}
Alternate implementation using Object.keys fanciness:
var myObj = {
'b': 'asdsadfd',
'c': 'masdasaf',
'a': 'dsfdsfsdf'
},
keys = Object.keys(myObj),
i, len = keys.length;
keys.sort();
for (i = 0; i < len; i++) {
k = keys[i];
console.log(k + ':' + myObj[k]);
}
1Not to be pedantic, but there's no such thing as a JSON object.
A lot of people have mention that "objects cannot be sorted", but after that they are giving you a solution which works. Paradox, isn't it?
No one mention why those solutions are working. They are, because in most of the browser's implementations values in objects are stored in the order in which they were added. That's why if you create new object from sorted list of keys it's returning an expected result.
And I think that we could add one more solution – ES5 functional way:
function sortObject(obj) {
return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
}
ES2015 version of above (formatted to "one-liner"):
const sortObject = o => Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {})
Short explanation of above examples (as asked in comments):
Object.keys is giving us a list of keys in provided object (obj or o), then we're sorting those using default sorting algorithm, next .reduce is used to convert that array back into an object, but this time with all of the keys sorted.
Guys I'm figuratively shocked! Sure all answers are somewhat old, but no one did even mention the stability in sorting! So bear with me I'll try my best to answer the question itself and go into details here. So I'm going to apologize now it will be a lot to read.
Since it is 2018 I will only use ES6, the Polyfills are all available at the MDN docs, which I will link at the given part.
Answer to the question:
If your keys are only numbers then you can safely use Object.keys() together with Array.prototype.reduce() to return the sorted object:
// Only numbers to show it will be sorted.
const testObj = {
'2000': 'Articel1',
'4000': 'Articel2',
'1000': 'Articel3',
'3000': 'Articel4',
};
// I'll explain what reduces does after the answer.
console.log(Object.keys(testObj).reduce((accumulator, currentValue) => {
accumulator[currentValue] = testObj[currentValue];
return accumulator;
}, {}));
/**
* expected output:
* {
* '1000': 'Articel3',
* '2000': 'Articel1',
* '3000': 'Articel4',
* '4000': 'Articel2'
* }
*/
// if needed here is the one liner:
console.log(Object.keys(testObj).reduce((a, c) => (a[c] = testObj[c], a), {}));
However if you are working with strings I highly recommend chaining Array.prototype.sort() into all of this:
// String example
const testObj = {
'a1d78eg8fdg387fg38': 'Articel1',
'z12989dh89h31d9h39': 'Articel2',
'f1203391dhj32189h2': 'Articel3',
'b10939hd83f9032003': 'Articel4',
};
// Chained sort into all of this.
console.log(Object.keys(testObj).sort().reduce((accumulator, currentValue) => {
accumulator[currentValue] = testObj[currentValue];
return accumulator;
}, {}));
/**
* expected output:
* {
* a1d78eg8fdg387fg38: 'Articel1',
* b10939hd83f9032003: 'Articel4',
* f1203391dhj32189h2: 'Articel3',
* z12989dh89h31d9h39: 'Articel2'
* }
*/
// again the one liner:
console.log(Object.keys(testObj).sort().reduce((a, c) => (a[c] = testObj[c], a), {}));
If someone is wondering what reduce does:
// Will return Keys of object as an array (sorted if only numbers or single strings like a,b,c).
Object.keys(testObj)
// Chaining reduce to the returned array from Object.keys().
// Array.prototype.reduce() takes one callback
// (and another param look at the last line) and passes 4 arguments to it:
// accumulator, currentValue, currentIndex and array
.reduce((accumulator, currentValue) => {
// setting the accumulator (sorted new object) with the actual property from old (unsorted) object.
accumulator[currentValue] = testObj[currentValue];
// returning the newly sorted object for the next element in array.
return accumulator;
// the empty object {} ist the initial value for Array.prototype.reduce().
}, {});
If needed here is the explanation for the one liner:
Object.keys(testObj).reduce(
// Arrow function as callback parameter.
(a, c) =>
// parenthesis return! so we can safe the return and write only (..., a);
(a[c] = testObj[c], a)
// initial value for reduce.
,{}
);
Docs for reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Why use parenthesis on JavaScript return statements: http://jamesknelson.com/javascript-return-parenthesis/
Why Sorting is a bit complicated:
In short Object.keys() will return an array with the same order as we get with a normal loop:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
Object.keys() returns an array whose elements are strings
corresponding to the enumerable properties found directly upon object.
The ordering of the properties is the same as that given by looping
over the properties of the object manually.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Sidenote - you can use Object.keys() on arrays as well, keep in mind the index will be returned:
// simple array
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
But it is not as easy as shown by those examples, real world objects may contain numbers and alphabetical characters or even symbols (please don't do it).
Here is an example with all of them in one object:
// This is just to show what happens, please don't use symbols in keys.
const testObj = {
'1asc': '4444',
1000: 'a',
b: '1231',
'#01010101010': 'asd',
2: 'c'
};
console.log(Object.keys(testObj));
// output: [ '2', '1000', '1asc', 'b', '#01010101010' ]
Now if we use Array.prototype.sort() on the array above the output changes:
console.log(Object.keys(testObj).sort());
// output: [ '#01010101010', '1000', '1asc', '2', 'b' ]
Here is a quote from the docs:
The sort() method sorts the elements of an array in place and returns
the array. The sort is not necessarily stable. The default sort order
is according to string Unicode code points.
The time and space complexity of the sort cannot be guaranteed as it
is implementation dependent.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You have to make sure that one of them returns the desired output for you. In reallife examples people tend to mix up things expecially if you use different information inputs like APIs and Databases together.
So what's the big deal?
Well there are two articles which every programmer should understand:
In-place algorithm:
In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. In-place algorithm updates input sequence only through replacement or swapping of elements. An algorithm which is not in-place is sometimes called not-in-place or out-of-place.
So basically our old array will be overwritten! This is important if you want to keep the old array for other reasons. So keep this in mind.
Sorting algorithm
Stable sort algorithms sort identical elements in the same order that
they appear in the input. When sorting some kinds of data, only part
of the data is examined when determining the sort order. For example,
in the card sorting example to the right, the cards are being sorted
by their rank, and their suit is being ignored. This allows the
possibility of multiple different correctly sorted versions of the
original list. Stable sorting algorithms choose one of these,
according to the following rule: if two items compare as equal, like
the two 5 cards, then their relative order will be preserved, so that
if one came before the other in the input, it will also come before
the other in the output.
An example of stable sort on playing cards. When the cards are sorted
by rank with a stable sort, the two 5s must remain in the same order
in the sorted output that they were originally in. When they are
sorted with a non-stable sort, the 5s may end up in the opposite order
in the sorted output.
This shows that the sorting is right but it changed. So in the real world even if the sorting is correct we have to make sure that we get what we expect! This is super important keep this in mind as well. For more JavaScript examples look into the Array.prototype.sort() - docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
It's 2019 and we have a 2019 way to solve this :)
Object.fromEntries(Object.entries({b: 3, a:8, c:1}).sort())
ES6 - here is the 1 liner
var data = { zIndex:99,
name:'sravan',
age:25,
position:'architect',
amount:'100k',
manager:'mammu' };
console.log(Object.entries(data).sort().reduce( (o,[k,v]) => (o[k]=v,o), {} ));
This works for me
/**
* Return an Object sorted by it's Key
*/
var sortObjectByKey = function(obj){
var keys = [];
var sorted_obj = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
keys.push(key);
}
}
// sort keys
keys.sort();
// create new array based on Sorted Keys
jQuery.each(keys, function(i, key){
sorted_obj[key] = obj[key];
});
return sorted_obj;
};
This is an old question, but taking the cue from Mathias Bynens' answer, I've made a short version to sort the current object, without much overhead.
Object.keys(unordered).sort().forEach(function(key) {
var value = unordered[key];
delete unordered[key];
unordered[key] = value;
});
after the code execution, the "unordered" object itself will have the keys alphabetically sorted.
Using lodash this will work:
some_map = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
// perform a function in order of ascending key
_(some_map).keys().sort().each(function (key) {
var value = some_map[key];
// do something
});
// or alternatively to build a sorted list
sorted_list = _(some_map).keys().sort().map(function (key) {
var value = some_map[key];
// return something that shall become an item in the sorted list
}).value();
Just food for thought.
Suppose it could be useful in VisualStudio debugger which shows unordered object properties.
(function(s) {
var t = {};
Object.keys(s).sort().forEach(function(k) {
t[k] = s[k]
});
return t
})({
b: 2,
a: 1,
c: 3
});
The same as inline version:
(function(s){var t={};Object.keys(s).sort().forEach(function(k){t[k]=s[k]});return t})({b:2,a:1,c:3})
I am actually very surprised that over 30 answers were given, and yet none gave a full deep solution for this problem. Some had shallow solution, while others had deep but faulty (it'll crash if undefined, function or symbol will be in the json).
Here is the full solution:
function sortObject(unordered, sortArrays = false) {
if (!unordered || typeof unordered !== 'object') {
return unordered;
}
if (Array.isArray(unordered)) {
const newArr = unordered.map((item) => sortObject(item, sortArrays));
if (sortArrays) {
newArr.sort();
}
return newArr;
}
const ordered = {};
Object.keys(unordered)
.sort()
.forEach((key) => {
ordered[key] = sortObject(unordered[key], sortArrays);
});
return ordered;
}
const json = {
b: 5,
a: [2, 1],
d: {
b: undefined,
a: null,
c: false,
d: true,
g: '1',
f: [],
h: {},
i: 1n,
j: () => {},
k: Symbol('a')
},
c: [
{
b: 1,
a: 1
}
]
};
console.log(sortObject(json, true));
Underscore version:
function order(unordered)
{
return _.object(_.sortBy(_.pairs(unordered),function(o){return o[0]}));
}
If you don't trust your browser for keeping the order of the keys, I strongly suggest to rely on a ordered array of key-value paired arrays.
_.sortBy(_.pairs(c),function(o){return o[0]})
function sortObjectKeys(obj){
return Object.keys(obj).sort().reduce((acc,key)=>{
acc[key]=obj[key];
return acc;
},{});
}
sortObjectKeys({
telephone: '069911234124',
name: 'Lola',
access: true,
});
Maybe a bit more elegant form:
/**
* Sorts a key-value object by key, maintaining key to data correlations.
* #param {Object} src key-value object
* #returns {Object}
*/
var ksort = function ( src ) {
var keys = Object.keys( src ),
target = {};
keys.sort();
keys.forEach(function ( key ) {
target[ key ] = src[ key ];
});
return target;
};
// Usage
console.log(ksort({
a:1,
c:3,
b:2
}));
P.S. and the same with ES6+ syntax:
function ksort( src ) {
const keys = Object.keys( src );
keys.sort();
return keys.reduce(( target, key ) => {
target[ key ] = src[ key ];
return target;
}, {});
};
Here is a one line solution (not the most efficient but when it comes to thin objects like in your example I'd rather use native JS functions then messing up with sloppy loops)
const unordered = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
const ordered = Object.fromEntries(Object.entries(unordered).sort())
console.log(ordered); // a->b->c
// if keys are char/string
const sortObject = (obj) => Object.fromEntries(Object.entries(obj).sort( ));
let obj = { c: 3, a: 1 };
obj = sortObject(obj)
// if keys are numbers
const sortObject = (obj) => Object.fromEntries(Object.entries(obj).sort( (a,b)=>a-b ));
let obj = { 3: 'c', 1: 'a' };
obj = sortObject(obj)
const sortObjectByKeys = (object, asc = true) => Object.fromEntries(
Object.entries(object).sort(([k1], [k2]) => k1 < k2 ^ !asc ? -1 : 1),
)
const object = { b: 'asdsad', c: 'masdas', a: 'dsfdsfsdf' }
const orderedObject = sortObjectByKeys(object)
console.log(orderedObject)
recursive sort, for nested object and arrays
function sortObjectKeys(obj){
return Object.keys(obj).sort().reduce((acc,key)=>{
if (Array.isArray(obj[key])){
acc[key]=obj[key].map(sortObjectKeys);
}
if (typeof obj[key] === 'object'){
acc[key]=sortObjectKeys(obj[key]);
}
else{
acc[key]=obj[key];
}
return acc;
},{});
}
// test it
sortObjectKeys({
telephone: '069911234124',
name: 'Lola',
access: true,
cars: [
{name: 'Family', brand: 'Volvo', cc:1600},
{
name: 'City', brand: 'VW', cc:1200,
interior: {
wheel: 'plastic',
radio: 'blaupunkt'
}
},
{
cc:2600, name: 'Killer', brand: 'Plymouth',
interior: {
wheel: 'wooden',
radio: 'earache!'
}
},
]
});
Here is a clean lodash-based version that works with nested objects
/**
* Sort of the keys of an object alphabetically
*/
const sortKeys = function(obj) {
if(_.isArray(obj)) {
return obj.map(sortKeys);
}
if(_.isObject(obj)) {
return _.fromPairs(_.keys(obj).sort().map(key => [key, sortKeys(obj[key])]));
}
return obj;
};
It would be even cleaner if lodash had a toObject() method...
There's a great project by #sindresorhus called sort-keys that works awesome.
You can check its source code here:
https://github.com/sindresorhus/sort-keys
Or you can use it with npm:
$ npm install --save sort-keys
Here are also code examples from his readme
const sortKeys = require('sort-keys');
sortKeys({c: 0, a: 0, b: 0});
//=> {a: 0, b: 0, c: 0}
sortKeys({b: {b: 0, a: 0}, a: 0}, {deep: true});
//=> {a: 0, b: {a: 0, b: 0}}
sortKeys({c: 0, a: 0, b: 0}, {
compare: (a, b) => -a.localeCompare(b)
});
//=> {c: 0, b: 0, a: 0}
Object.keys(unordered).sort().reduce(
(acc,curr) => ({...acc, [curr]:unordered[curr]})
, {}
)
Use this code if you have nested objects or if you have nested array obj.
var sortObjectByKey = function(obj){
var keys = [];
var sorted_obj = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
keys.push(key);
}
}
// sort keys
keys.sort();
// create new array based on Sorted Keys
jQuery.each(keys, function(i, key){
var val = obj[key];
if(val instanceof Array){
//do for loop;
var arr = [];
jQuery.each(val,function(){
arr.push(sortObjectByKey(this));
});
val = arr;
}else if(val instanceof Object){
val = sortObjectByKey(val)
}
sorted_obj[key] = val;
});
return sorted_obj;
};
As already mentioned, objects are unordered.
However...
You may find this idiom useful:
var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };
var kv = [];
for (var k in o) {
kv.push([k, o[k]]);
}
kv.sort()
You can then iterate through kv and do whatever you wish.
> kv.sort()
[ [ 'a', 'dsfdsfsdf' ],
[ 'b', 'asdsad' ],
[ 'c', 'masdas' ] ]
Just use lodash to unzip map and sortBy first value of pair and zip again it will return sorted key.
If you want sortby value change pair index to 1 instead of 0
var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };
console.log(_(o).toPairs().sortBy(0).fromPairs().value())
Sorts keys recursively while preserving references.
function sortKeys(o){
if(o && o.constructor === Array)
o.forEach(i=>sortKeys(i));
else if(o && o.constructor === Object)
Object.entries(o).sort((a,b)=>a[0]>b[0]?1:-1).forEach(e=>{
sortKeys(e[1]);
delete o[e[0]];
o[e[0]] = e[1];
});
}
Example:
let x = {d:3, c:{g:20, a:[3,2,{s:200, a:100}]}, a:1};
let y = x.c;
let z = x.c.a[2];
sortKeys(x);
console.log(x); // {a: 1, c: {a: [3, 2, {a: 1, s: 2}], g: 2}, d: 3}
console.log(y); // {a: [3, 2, {a: 100, s: 200}}, g: 20}
console.log(z); // {a: 100, s: 200}
This is a lightweight solution to everything I need for JSON sorting.
function sortObj(obj) {
if (typeof obj !== "object" || obj === null)
return obj;
if (Array.isArray(obj))
return obj.map((e) => sortObj(e)).sort();
return Object.keys(obj).sort().reduce((sorted, k) => {
sorted[k] = sortObj(obj[k]);
return sorted;
}, {});
}
Solution:
function getSortedObject(object) {
var sortedObject = {};
var keys = Object.keys(object);
keys.sort();
for (var i = 0, size = keys.length; i < size; i++) {
key = keys[i];
value = object[key];
sortedObject[key] = value;
}
return sortedObject;
}
// Test run
getSortedObject({d: 4, a: 1, b: 2, c: 3});
Explanation:
Many JavaScript runtimes store values inside an object in the order in which they are added.
To sort the properties of an object by their keys you can make use of the Object.keys function which will return an array of keys. The array of keys can then be sorted by the Array.prototype.sort() method which sorts the elements of an array in place (no need to assign them to a new variable).
Once the keys are sorted you can start using them one-by-one to access the contents of the old object to fill a new object (which is now sorted).
Below is an example of the procedure (you can test it in your targeted browsers):
/**
* Returns a copy of an object, which is ordered by the keys of the original object.
*
* #param {Object} object - The original object.
* #returns {Object} Copy of the original object sorted by keys.
*/
function getSortedObject(object) {
// New object which will be returned with sorted keys
var sortedObject = {};
// Get array of keys from the old/current object
var keys = Object.keys(object);
// Sort keys (in place)
keys.sort();
// Use sorted keys to copy values from old object to the new one
for (var i = 0, size = keys.length; i < size; i++) {
key = keys[i];
value = object[key];
sortedObject[key] = value;
}
// Return the new object
return sortedObject;
}
/**
* Test run
*/
var unsortedObject = {
d: 4,
a: 1,
b: 2,
c: 3
};
var sortedObject = getSortedObject(unsortedObject);
for (var key in sortedObject) {
var text = "Key: " + key + ", Value: " + sortedObject[key];
var paragraph = document.createElement('p');
paragraph.textContent = text;
document.body.appendChild(paragraph);
}
Note: Object.keys is an ECMAScript 5.1 method but here is a polyfill for older browsers:
if (!Object.keys) {
Object.keys = function (object) {
var key = [];
var property = undefined;
for (property in object) {
if (Object.prototype.hasOwnProperty.call(object, property)) {
key.push(property);
}
}
return key;
};
}
I transfered some Java enums to javascript objects.
These objects returned correct arrays for me. if object keys are mixed type (string, int, char), there is a problem.
var Helper = {
isEmpty: function (obj) {
return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;
},
isObject: function (obj) {
return (typeof obj === 'object');
},
sortObjectKeys: function (object) {
return Object.keys(object)
.sort(function (a, b) {
c = a - b;
return c
});
},
containsItem: function (arr, item) {
if (arr && Array.isArray(arr)) {
return arr.indexOf(item) > -1;
} else {
return arr === item;
}
},
pushArray: function (arr1, arr2) {
if (arr1 && arr2 && Array.isArray(arr1)) {
arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);
}
}
};
function TypeHelper() {
var _types = arguments[0],
_defTypeIndex = 0,
_currentType,
_value;
if (arguments.length == 2) {
_defTypeIndex = arguments[1];
}
Object.defineProperties(this, {
Key: {
get: function () {
return _currentType;
},
set: function (val) {
_currentType.setType(val, true);
},
enumerable: true
},
Value: {
get: function () {
return _types[_currentType];
},
set: function (val) {
_value.setType(val, false);
},
enumerable: true
}
});
this.getAsList = function (keys) {
var list = [];
Helper.sortObjectKeys(_types).forEach(function (key, idx, array) {
if (key && _types[key]) {
if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {
var json = {};
json.Key = key;
json.Value = _types[key];
Helper.pushArray(list, json);
}
}
});
return list;
};
this.setType = function (value, isKey) {
if (!Helper.isEmpty(value)) {
Object.keys(_types).forEach(function (key, idx, array) {
if (Helper.isObject(value)) {
if (value && value.Key == key) {
_currentType = key;
}
} else if (isKey) {
if (value && value.toString() == key.toString()) {
_currentType = key;
}
} else if (value && value.toString() == _types[key]) {
_currentType = key;
}
});
} else {
this.setDefaultType();
}
return isKey ? _types[_currentType] : _currentType;
};
this.setTypeByIndex = function (index) {
var keys = Helper.sortObjectKeys(_types);
for (var i = 0; i < keys.length; i++) {
if (index === i) {
_currentType = keys[index];
break;
}
}
};
this.setDefaultType = function () {
this.setTypeByIndex(_defTypeIndex);
};
this.setDefaultType();
}
var TypeA = {
"-1": "Any",
"2": "2L",
"100": "100L",
"200": "200L",
"1000": "1000L"
};
var TypeB = {
"U": "Any",
"W": "1L",
"V": "2L",
"A": "100L",
"Z": "200L",
"K": "1000L"
};
console.log('keys of TypeA', Helper.sortObjectKeys(TypeA));//keys of TypeA ["-1", "2", "100", "200", "1000"]
console.log('keys of TypeB', Helper.sortObjectKeys(TypeB));//keys of TypeB ["U", "W", "V", "A", "Z", "K"]
var objectTypeA = new TypeHelper(TypeA),
objectTypeB = new TypeHelper(TypeB);
console.log('list of objectA = ', objectTypeA.getAsList());
console.log('list of objectB = ', objectTypeB.getAsList());
Types:
var TypeA = {
"-1": "Any",
"2": "2L",
"100": "100L",
"200": "200L",
"1000": "1000L"
};
var TypeB = {
"U": "Any",
"W": "1L",
"V": "2L",
"A": "100L",
"Z": "200L",
"K": "1000L"
};
Sorted Keys(output):
Key list of TypeA -> ["-1", "2", "100", "200", "1000"]
Key list of TypeB -> ["U", "W", "V", "A", "Z", "K"]
The one line:
Object.entries(unordered)
.sort(([keyA], [keyB]) => keyA > keyB)
.reduce((obj, [key,value]) => Object.assign(obj, {[key]: value}), {})
Pure JavaScript answer to sort an Object. This is the only answer that I know of that will handle negative numbers. This function is for sorting numerical Objects.
Input
obj = {1000: {}, -1200: {}, 10000: {}, 200: {}};
function osort(obj) {
var keys = Object.keys(obj);
var len = keys.length;
var rObj = [];
var rK = [];
var t = Object.keys(obj).length;
while(t > rK.length) {
var l = null;
for(var x in keys) {
if(l && parseInt(keys[x]) < parseInt(l)) {
l = keys[x];
k = x;
}
if(!l) { // Find Lowest
var l = keys[x];
var k = x;
}
}
delete keys[k];
rK.push(l);
}
for (var i = 0; i < len; i++) {
k = rK[i];
rObj.push(obj[k]);
}
return rObj;
}
The output will be an object sorted by those numbers with new keys starting at 0.

sort object properties and JSON.stringify

My application has a large array of objects, which I stringify and save them to the disk. Unfortunately, when the objects in the array are manipulated, and sometimes replaced, the properties on the objects are listed in different orders (their creation order?). When I do JSON.stringify() on the array and save it, a diff shows the properties getting listed in different orders, which is annoying when trying to merge the data further with diff and merging tools.
Ideally I would like to sort the properties of the objects in alphabetical order prior to performing the stringify, or as part of the stringify operation. There is code for manipulating the array objects in many places, and altering these to always create properties in an explicit order would be difficult.
Suggestions would be most welcome!
A condensed example:
obj = {}; obj.name="X"; obj.os="linux";
JSON.stringify(obj);
obj = {}; obj.os="linux"; obj.name="X";
JSON.stringify(obj);
The output of these two stringify calls are different, and showing up in a diff of my data, but my application doesn't care about the ordering of properties. The objects are constructed in many ways and places.
The simpler, modern and currently browser supported approach is simply this:
JSON.stringify(sortMyObj, Object.keys(sortMyObj).sort());
However, this method does remove any nested objects that aren't referenced and does not apply to objects within arrays. You will want to flatten the sorting object as well if you want something like this output:
{"a":{"h":4,"z":3},"b":2,"c":1}
You can do that with this:
var flattenObject = function(ob) {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object') {
var flatObject = flattenObject(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
var myFlattenedObj = flattenObject(sortMyObj);
JSON.stringify(myFlattenedObj, Object.keys(myFlattenedObj).sort());
To do it programmatically with something you can tweak yourself, you need to push the object property names into an array, then sort the array alphabetically and iterate through that array (which will be in the right order) and select each value from the object in that order. "hasOwnProperty" is checked also so you definitely have only the object's own properties. Here's an example:
var obj = {"a":1,"b":2,"c":3};
function iterateObjectAlphabetically(obj, callback) {
var arr = [],
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
arr.push(i);
}
}
arr.sort();
for (i = 0; i < arr.length; i++) {
var key = obj[arr[i]];
//console.log( obj[arr[i]] ); //here is the sorted value
//do what you want with the object property
if (callback) {
// callback returns arguments for value, key and original object
callback(obj[arr[i]], arr[i], obj);
}
}
}
iterateObjectAlphabetically(obj, function(val, key, obj) {
//do something here
});
Again, this should guarantee that you iterate through in alphabetical order.
Finally, taking it further for the simplest way, this library will recursively allow you to sort any JSON you pass into it: https://www.npmjs.com/package/json-stable-stringify
var stringify = require('json-stable-stringify');
var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
console.log(stringify(obj));
Output
{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}
I don't understand why the complexity of the current best answers is needed, to get all the keys recursively. Unless perfect performance is needed, it seems to me that we can just call JSON.stringify() twice, the first time to get all the keys, and the second time, to really do the job. That way, all the recursion complexity is handled by stringify, and we know that it knows its stuff, and how to handle each object type:
function JSONstringifyOrder(obj, space)
{
const allKeys = new Set();
JSON.stringify(obj, (key, value) => (allKeys.add(key), value));
return JSON.stringify(obj, Array.from(allKeys).sort(), space);
}
Or if you want to support older browsers:
function JSONstringifyOrder(obj, space)
{
var allKeys = [];
var seen = {};
JSON.stringify(obj, function (key, value) {
if (!(key in seen)) {
allKeys.push(key);
seen[key] = null;
}
return value;
});
allKeys.sort();
return JSON.stringify(obj, allKeys, space);
}
I think that if you are in control of the JSON generation (and it sounds like you are), then for your purposes this might be a good solution: json-stable-stringify
From the project website:
deterministic JSON.stringify() with custom sorting to get
deterministic hashes from stringified results
If the JSON produced is deterministic you should be able to easily diff/merge it.
You can pass a sorted array of the property names as the second argument of JSON.stringify():
JSON.stringify(obj, Object.keys(obj).sort())
JSON.stringify() replacer function for having object keys sorted in output (supports deeply nested objects).
const replacer = (key, value) =>
value instanceof Object && !(value instanceof Array) ?
Object.keys(value)
.sort()
.reduce((sorted, key) => {
sorted[key] = value[key];
return sorted
}, {}) :
value;
// Usage
// JSON.stringify({c: 1, a: { d: 0, c: 1, e: {a: 0, 1: 4}}}, replacer);
GitHub Gist page here.
Update 2018-7-24:
This version sorts nested objects and supports array as well:
function sortObjByKey(value) {
return (typeof value === 'object') ?
(Array.isArray(value) ?
value.map(sortObjByKey) :
Object.keys(value).sort().reduce(
(o, key) => {
const v = value[key];
o[key] = sortObjByKey(v);
return o;
}, {})
) :
value;
}
function orderedJsonStringify(obj) {
return JSON.stringify(sortObjByKey(obj));
}
Test case:
describe('orderedJsonStringify', () => {
it('make properties in order', () => {
const obj = {
name: 'foo',
arr: [
{ x: 1, y: 2 },
{ y: 4, x: 3 },
],
value: { y: 2, x: 1, },
};
expect(orderedJsonStringify(obj))
.to.equal('{"arr":[{"x":1,"y":2},{"x":3,"y":4}],"name":"foo","value":{"x":1,"y":2}}');
});
it('support array', () => {
const obj = [
{ x: 1, y: 2 },
{ y: 4, x: 3 },
];
expect(orderedJsonStringify(obj))
.to.equal('[{"x":1,"y":2},{"x":3,"y":4}]');
});
});
Deprecated answer:
A concise version in ES2016.
Credit to #codename , from https://stackoverflow.com/a/29622653/94148
function orderedJsonStringify(o) {
return JSON.stringify(Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {}));
}
This is same as Satpal Singh's answer
function stringifyJSON(obj){
keys = [];
if(obj){
for(var key in obj){
keys.push(key);
}
}
keys.sort();
var tObj = {};
var key;
for(var index in keys){
key = keys[index];
tObj[ key ] = obj[ key ];
}
return JSON.stringify(tObj);
}
obj1 = {}; obj1.os="linux"; obj1.name="X";
stringifyJSON(obj1); //returns "{"name":"X","os":"linux"}"
obj2 = {}; obj2.name="X"; obj2.os="linux";
stringifyJSON(obj2); //returns "{"name":"X","os":"linux"}"
A recursive and simplified answer:
function sortObject(obj) {
if(typeof obj !== 'object')
return obj
var temp = {};
var keys = [];
for(var key in obj)
keys.push(key);
keys.sort();
for(var index in keys)
temp[keys[index]] = sortObject(obj[keys[index]]);
return temp;
}
var str = JSON.stringify(sortObject(obj), undefined, 4);
You can sort object by property name in EcmaScript 2015
function sortObjectByPropertyName(obj) {
return Object.keys(obj).sort().reduce((c, d) => (c[d] = obj[d], c), {});
}
You can add a custom toJSON function to your object which you can use to customise the output. Inside the function, adding current properties to a new object in a specific order should preserve that order when stringified.
See here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
There's no in-built method for controlling ordering because JSON data is meant to be accessed by keys.
Here's a jsfiddle with a small example:
http://jsfiddle.net/Eq2Yw/
Try commenting out the toJSON function - the order of the properties is reversed. Please be aware that this may be browser-specific, i.e. ordering is not officially supported in the specification. It works in the current version of Firefox, but if you want a 100% robust solution, you may have to write your own stringifier function.
Edit:
Also see this SO question regarding stringify's non-deterministic output, especially Daff's details about browser differences:
How to deterministically verify that a JSON object hasn't been modified?
I took the answer from #Jason Parham and made some improvements
function sortObject(obj, arraySorter) {
if(typeof obj !== 'object')
return obj
if (Array.isArray(obj)) {
if (arraySorter) {
obj.sort(arraySorter);
}
for (var i = 0; i < obj.length; i++) {
obj[i] = sortObject(obj[i], arraySorter);
}
return obj;
}
var temp = {};
var keys = [];
for(var key in obj)
keys.push(key);
keys.sort();
for(var index in keys)
temp[keys[index]] = sortObject(obj[keys[index]], arraySorter);
return temp;
}
This fixes the issue of arrays being converted to objects, and it also allows you to define how to sort arrays.
Example:
var data = { content: [{id: 3}, {id: 1}, {id: 2}] };
sortObject(data, (i1, i2) => i1.id - i2.id)
output:
{content:[{id:1},{id:2},{id:3}]}
I just rewrote one of mentioned examples to use it in stringify
const stringifySort = (key, value) => {
if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
return Object.keys(value).sort().reduce((obj, key) => (obj[key]=value[key], obj), {});
};
JSON.stringify({name:"X", os:"linux"}, stringifySort);
The accepted answer does not work for me for nested objects for some reason. This led me to code up my own. As it's late 2019 when I write this, there are a few more options available within the language.
Update: I believe David Furlong's answer is a preferable approach to my earlier attempt, and I have riffed off that. Mine relies on support for Object.entries(...), so no Internet Explorer support.
function normalize(sortingFunction) {
return function(key, value) {
if (typeof value === 'object' && !Array.isArray(value)) {
return Object
.entries(value)
.sort(sortingFunction || undefined)
.reduce((acc, entry) => {
acc[entry[0]] = entry[1];
return acc;
}, {});
}
return value;
}
}
JSON.stringify(obj, normalize(), 2);
--
KEEPING THIS OLDER VERSION FOR HISTORICAL REFERENCE
I found that a simple, flat array of all keys in the object will work. In almost all browsers (not Edge or Internet explorer, predictably) and Node 12+ there is a fairly short solution now that Array.prototype.flatMap(...) is available. (The lodash equivalent would work too.) I have only tested in Safari, Chrome, and Firefox, but I see no reason why it wouldn't work anywhere else that supports flatMap and standard JSON.stringify(...).
function flattenEntries([key, value]) {
return (typeof value !== 'object')
? [ [ key, value ] ]
: [ [ key, value ], ...Object.entries(value).flatMap(flattenEntries) ];
}
function sortedStringify(obj, sorter, indent = 2) {
const allEntries = Object.entries(obj).flatMap(flattenEntries);
const sorted = allEntries.sort(sorter || undefined).map(entry => entry[0]);
return JSON.stringify(obj, sorted, indent);
}
With this, you can stringify with no 3rd-party dependencies and even pass in your own sort algorithm that sorts on the key-value entry pairs, so you can sort by key, payload, or a combination of the two. Works for nested objects, arrays, and any mixture of plain old data types.
const obj = {
"c": {
"z": 4,
"x": 3,
"y": [
2048,
1999,
{
"x": false,
"g": "help",
"f": 5
}
]
},
"a": 2,
"b": 1
};
console.log(sortedStringify(obj, null, 2));
Prints:
{
"a": 2,
"b": 1,
"c": {
"x": 3,
"y": [
2048,
1999,
{
"f": 5,
"g": "help",
"x": false
}
],
"z": 4
}
}
If you must have compatibility with older JavaScript engines, you could use these slightly more verbose versions that emulate flatMap behavior. Client must support at least ES5, so no Internet Explorer 8 or below.
These will return the same result as above.
function flattenEntries([key, value]) {
if (typeof value !== 'object') {
return [ [ key, value ] ];
}
const nestedEntries = Object
.entries(value)
.map(flattenEntries)
.reduce((acc, arr) => acc.concat(arr), []);
nestedEntries.unshift([ key, value ]);
return nestedEntries;
}
function sortedStringify(obj, sorter, indent = 2) {
const sortedKeys = Object
.entries(obj)
.map(flattenEntries)
.reduce((acc, arr) => acc.concat(arr), [])
.sort(sorter || undefined)
.map(entry => entry[0]);
return JSON.stringify(obj, sortedKeys, indent);
}
An additional solution that works for nested objects as well:
const myFunc = (key) =>
JSON.stringify(key, (_, v) =>
v.constructor === Object ? Object.entries(v).sort() : v
);
const jsonFunc = JSON.stringify;
const obj1 = {
key1: "value1",
key2: {
key3: "value2",
key4: "value3",
},
};
const obj2 = {
key2: {
key4: "value3",
key3: "value2",
},
key1: "value1",
};
console.log(`JSON: ${jsonFunc(obj1) === jsonFunc(obj2)}`);
console.log(`My: ${myFunc(obj1) === myFunc(obj2)}`);
Works with lodash, nested objects, any value of object attribute:
function sort(myObj) {
var sortedObj = {};
Object.keys(myObj).sort().forEach(key => {
sortedObj[key] = _.isPlainObject(myObj[key]) ? sort(myObj[key]) : myObj[key]
})
return sortedObj;
}
JSON.stringify(sort(yourObj), null, 2)
It relies on Chrome's and Node's behaviour that the first key assigned to an object is outputted first by JSON.stringify.
After all, it needs an Array that caches all keys in the nested object (otherwise it will omit the uncached keys.) The oldest answer is just plain wrong, because second argument doesn't care about dot-notation. So, the answer (using Set) becomes.
function stableStringify (obj) {
const keys = new Set()
const getAndSortKeys = (a) => {
if (a) {
if (typeof a === 'object' && a.toString() === '[object Object]') {
Object.keys(a).map((k) => {
keys.add(k)
getAndSortKeys(a[k])
})
} else if (Array.isArray(a)) {
a.map((el) => getAndSortKeys(el))
}
}
}
getAndSortKeys(obj)
return JSON.stringify(obj, Array.from(keys).sort())
}
Try:
function obj(){
this.name = '';
this.os = '';
}
a = new obj();
a.name = 'X',
a.os = 'linux';
JSON.stringify(a);
b = new obj();
b.os = 'linux';
b.name = 'X',
JSON.stringify(b);
I made a function to sort object, and with callback .. which actually create a new object
function sortObj( obj , callback ) {
var r = [] ;
for ( var i in obj ){
if ( obj.hasOwnProperty( i ) ) {
r.push( { key: i , value : obj[i] } );
}
}
return r.sort( callback ).reduce( function( obj , n ){
obj[ n.key ] = n.value ;
return obj;
},{});
}
and call it with object .
var obj = {
name : "anu",
os : "windows",
value : 'msio',
};
var result = sortObj( obj , function( a, b ){
return a.key < b.key ;
});
JSON.stringify( result )
which prints {"value":"msio","os":"windows","name":"anu"} , and for sorting with value .
var result = sortObj( obj , function( a, b ){
return a.value < b.value ;
});
JSON.stringify( result )
which prints {"os":"windows","value":"msio","name":"anu"}
If objects in the list does not have same properties, generate a combined master object before stringify:
let arr=[ <object1>, <object2>, ... ]
let o = {}
for ( let i = 0; i < arr.length; i++ ) {
Object.assign( o, arr[i] );
}
JSON.stringify( arr, Object.keys( o ).sort() );
function FlatternInSort( obj ) {
if( typeof obj === 'object' )
{
if( obj.constructor === Object )
{ //here use underscore.js
let PaireStr = _( obj ).chain().pairs().sortBy( p => p[0] ).map( p => p.map( FlatternInSort ).join( ':' )).value().join( ',' );
return '{' + PaireStr + '}';
}
return '[' + obj.map( FlatternInSort ).join( ',' ) + ']';
}
return JSON.stringify( obj );
}
// example as below. in each layer, for objects like {}, flattened in key sort. for arrays, numbers or strings, flattened like/with JSON.stringify.
FlatternInSort( { c:9, b: { y: 4, z: 2, e: 9 }, F:4, a:[{j:8, h:3},{a:3,b:7}] } )
"{"F":4,"a":[{"h":3,"j":8},{"a":3,"b":7}],"b":{"e":9,"y":4,"z":2},"c":9}"
Extending AJP's answer, to handle arrays:
function sort(myObj) {
var sortedObj = {};
Object.keys(myObj).sort().forEach(key => {
sortedObj[key] = _.isPlainObject(myObj[key]) ? sort(myObj[key]) : _.isArray(myObj[key])? myObj[key].map(sort) : myObj[key]
})
return sortedObj;
}
Surprised nobody has mentioned lodash's isEqual function.
Performs a deep comparison between two values to determine if they are
equivalent.
Note: This method supports comparing arrays, array buffers, booleans,
date objects, error objects, maps, numbers, Object objects, regexes,
sets, strings, symbols, and typed arrays. Object objects are compared
by their own, not inherited, enumerable properties. Functions and DOM
nodes are compared by strict equality, i.e. ===.
https://lodash.com/docs/4.17.11#isEqual
With the original problem - keys being inconsistently ordered - it's a great solution - and of course it will just stop if it finds a conflict instead of blindly serializing the whole object.
To avoid importing the whole library you do this:
import { isEqual } from "lodash-es";
Bonus example:
You can also use this with RxJS with this custom operator
export const distinctUntilEqualChanged = <T>(): MonoTypeOperatorFunction<T> =>
pipe(distinctUntilChanged(isEqual));
Here is a clone approach...clone the object before converting to json:
function sort(o: any): any {
if (null === o) return o;
if (undefined === o) return o;
if (typeof o !== "object") return o;
if (Array.isArray(o)) {
return o.map((item) => sort(item));
}
const keys = Object.keys(o).sort();
const result = <any>{};
keys.forEach((k) => (result[k] = sort(o[k])));
return result;
}
If is very new but seems to work on package.json files fine.
Don't be confused with the object monitoring of Chrome debugger. It shows sorted keys in object, even though actually it is not sorted. You have to sort the object before you stringify it.
Before I found libs like fast-json-stable-stringify (haven't tested it in production myself), I was doing it this way:
import { flatten } from "flat";
import { set } from 'lodash/fp';
const sortJson = (jsonString) => {
const object = JSON.parse(jsonString);
const flatObject = flatten(object);
const propsSorted = Object.entries(flatObject).map(([key, value]) => ({ key, value })).sort((a, b) => a.key.localeCompare(b.key));
const objectSorted = propsSorted.reduce((object, { key, value }) => set(key, value, object), {});
return JSON.stringify(objectSorted);
};
const originalJson = JSON.stringify({ c: { z: 3, x: 1, y: 2 }, a: true, b: [ 'a', 'b', 'c' ] });
console.log(sortJson(originalJson)); // {"a":true,"b":["a","b","c"],"c":{"x":1,"y":2,"z":3}}
There is Array.sort method which can be helpful for you. For example:
yourBigArray.sort(function(a,b){
//custom sorting mechanism
});

Categories