Related
I am trying to create a deep copy map method for my Redux project that will work with objects rather than arrays. I read that in Redux each state should not change anything in the previous states.
export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {
output[key] = callback.call(this, {...object[key]});
return output;
},
{});
}
It works:
return mapCopy(state, e => {
if (e.id === action.id) {
e.title = 'new item';
}
return e;
})
However it does not deep copy inner items so I need to tweak it to:
export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {
let newObject = {...object[key]};
newObject.style = {...newObject.style};
newObject.data = {...newObject.data};
output[key] = callback.call(this, newObject);
return output;
}, {});
}
This is less elegant as it requires to know which objects are passed.
Is there a way in ES6 to use the spread syntax to deep copy an object?
Use JSON for deep copy
var newObject = JSON.parse(JSON.stringify(oldObject))
var oldObject = {
name: 'A',
address: {
street: 'Station Road',
city: 'Pune'
}
}
var newObject = JSON.parse(JSON.stringify(oldObject));
newObject.address.city = 'Delhi';
console.log('newObject');
console.log(newObject);
console.log('oldObject');
console.log(oldObject);
No such functionality is built-in to ES6. I think you have a couple of options depending on what you want to do.
If you really want to deep copy:
Use a library. For example, lodash has a cloneDeep method.
Implement your own cloning function.
Alternative Solution To Your Specific Problem (No Deep Copy)
However, I think, if you're willing to change a couple things, you can save yourself some work. I'm assuming you control all call sites to your function.
Specify that all callbacks passed to mapCopy must return new objects instead of mutating the existing object. For example:
mapCopy(state, e => {
if (e.id === action.id) {
return Object.assign({}, e, {
title: 'new item'
});
} else {
return e;
}
});
This makes use of Object.assign to create a new object, sets properties of e on that new object, then sets a new title on that new object. This means you never mutate existing objects and only create new ones when necessary.
mapCopy can be really simple now:
export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {
output[key] = callback.call(this, object[key]);
return output;
}, {});
}
Essentially, mapCopy is trusting its callers to do the right thing. This is why I said this assumes you control all call sites.
From MDN
Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).
Personally, I suggest using Lodash's cloneDeep function for multi-level object/array cloning.
Here is a working example:
const arr1 = [{ 'a': 1 }];
const arr2 = [...arr1];
const arr3 = _.clone(arr1);
const arr4 = arr1.slice();
const arr5 = _.cloneDeep(arr1);
const arr6 = [...{...arr1}]; // a bit ugly syntax but it is working!
// first level
console.log(arr1 === arr2); // false
console.log(arr1 === arr3); // false
console.log(arr1 === arr4); // false
console.log(arr1 === arr5); // false
console.log(arr1 === arr6); // false
// second level
console.log(arr1[0] === arr2[0]); // true
console.log(arr1[0] === arr3[0]); // true
console.log(arr1[0] === arr4[0]); // true
console.log(arr1[0] === arr5[0]); // false
console.log(arr1[0] === arr6[0]); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
I often use this:
function deepCopy(obj) {
if(typeof obj !== 'object' || obj === null) {
return obj;
}
if(obj instanceof Date) {
return new Date(obj.getTime());
}
if(obj instanceof Array) {
return obj.reduce((arr, item, i) => {
arr[i] = deepCopy(item);
return arr;
}, []);
}
if(obj instanceof Object) {
return Object.keys(obj).reduce((newObj, key) => {
newObj[key] = deepCopy(obj[key]);
return newObj;
}, {})
}
}
You can use structuredClone() like the following:
const myOriginal = {
title: "Full Stack JavaScript Developer",
info: {
firstname: "Abolfazl",
surname: "Roshanzamir",
age: 34
}
};
const myDeepCopy = structuredClone(myOriginal);
structuredClone()
You can use structuredClone() that is a built-in function for deep-copying.
Structured cloning addresses many (although not all) shortcomings of the JSON.stringify() technique.
Structured cloning can handle cyclical data structures,
support many built-in data types, and is generally more robust and often faster.
However, it still has some limitations that may catch you off-guard:
1-Prototypes : If you use structuredClone() with a class instance,
you’ll get a plain object as the return value, as structured cloning discards the object’s prototype chain.
2-Functions: If your object contains functions, they will be quietly discarded.
3- Non-cloneables: Some values are not structured cloneable, most notably Error and DOM nodes. It will cause structuredClone() to throw.
const myDeepCopy = structuredClone(myOriginal);
JSON.stringify
If you simply want to deep copy the object to another object,
all you will need to do is JSON.stringify the object and parse it using JSON.parse afterward.
This will essentially perform deep copying of the object.
let user1 = {
name: 'Abolfazl Roshanzamir',
age: 34,
university: {
name: 'Shiraz Bahonar University'
}
};
let user2 = JSON.parse(JSON.stringify(user1));
user2.name = 'Andy Madadian';
user2.university.name = 'Kerman Bahonar University'
console.log(user2);
// { name: 'Andy Madadian', age: 33, university: { name: 'Kerman Bahonar University' } }
console.log(user1);
// { name: 'Abolfazl Roshanzamir', age: 33, university: { name: 'Shiraz Bahonar University' } }
Spread operator / Object.assign()
One way to create a shallow copy in JavaScript using the object spread operator ... or Object.assign() like the following:
const myShallowCopySpread = {...myOriginal};
const myShallowCopyObjectAssign=Object.assign({},obj)
Performance
When it comes to performance the creator Surma has pointed out that JSON.Parse() can be a bit faster for small objects. But when you have a large object, complex object
structuredClone() starts to get significantly faster.
Browser support is pretty fantastic And even is supported by Node.js.
const a = {
foods: {
dinner: 'Pasta'
}
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta
Using JSON.stringify and JSON.parse is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.
Here's my deep copy algorithm.
const DeepClone = (obj) => {
if(obj===null||typeof(obj)!=='object')return null;
let newObj = { ...obj };
for (let prop in obj) {
if (
typeof obj[prop] === "object" ||
typeof obj[prop] === "function"
) {
newObj[prop] = DeepClone(obj[prop]);
}
}
return newObj;
};
// use: clone( <thing to copy> ) returns <new copy>
// untested use at own risk
function clone(o, m){
// return non object values
if('object' !==typeof o) return o
// m: a map of old refs to new object refs to stop recursion
if('object' !==typeof m || null ===m) m =new WeakMap()
var n =m.get(o)
if('undefined' !==typeof n) return n
// shallow/leaf clone object
var c =Object.getPrototypeOf(o).constructor
// TODO: specialize copies for expected built in types i.e. Date etc
switch(c) {
// shouldn't be copied, keep reference
case Boolean:
case Error:
case Function:
case Number:
case Promise:
case String:
case Symbol:
case WeakMap:
case WeakSet:
n =o
break;
// array like/collection objects
case Array:
m.set(o, n =o.slice(0))
// recursive copy for child objects
n.forEach(function(v,i){
if('object' ===typeof v) n[i] =clone(v, m)
});
break;
case ArrayBuffer:
m.set(o, n =o.slice(0))
break;
case DataView:
m.set(o, n =new (c)(clone(o.buffer, m), o.byteOffset, o.byteLength))
break;
case Map:
case Set:
m.set(o, n =new (c)(clone(Array.from(o.entries()), m)))
break;
case Int8Array:
case Uint8Array:
case Uint8ClampedArray:
case Int16Array:
case Uint16Array:
case Int32Array:
case Uint32Array:
case Float32Array:
case Float64Array:
m.set(o, n =new (c)(clone(o.buffer, m), o.byteOffset, o.length))
break;
// use built in copy constructor
case Date:
case RegExp:
m.set(o, n =new (c)(o))
break;
// fallback generic object copy
default:
m.set(o, n =Object.assign(new (c)(), o))
// recursive copy for child objects
for(c in n) if('object' ===typeof n[c]) n[c] =clone(n[c], m)
}
return n
}
Here is the deepClone function which handles all primitive, array, object, function data types
function deepClone(obj){
if(Array.isArray(obj)){
var arr = [];
for (var i = 0; i < obj.length; i++) {
arr[i] = deepClone(obj[i]);
}
return arr;
}
if(typeof(obj) == "object"){
var cloned = {};
for(let key in obj){
cloned[key] = deepClone(obj[key])
}
return cloned;
}
return obj;
}
console.log( deepClone(1) )
console.log( deepClone('abc') )
console.log( deepClone([1,2]) )
console.log( deepClone({a: 'abc', b: 'def'}) )
console.log( deepClone({
a: 'a',
num: 123,
func: function(){'hello'},
arr: [[1,2,3,[4,5]], 'def'],
obj: {
one: {
two: {
three: 3
}
}
}
}) )
function deepclone(obj) {
let newObj = {};
if (typeof obj === 'object') {
for (let key in obj) {
let property = obj[key],
type = typeof property;
switch (type) {
case 'object':
if( Object.prototype.toString.call( property ) === '[object Array]' ) {
newObj[key] = [];
for (let item of property) {
newObj[key].push(this.deepclone(item))
}
} else {
newObj[key] = deepclone(property);
}
break;
default:
newObj[key] = property;
break;
}
}
return newObj
} else {
return obj;
}
}
const cloneData = (dataArray) => {
newData= []
dataArray.forEach((value) => {
newData.push({...value})
})
return newData
}
a = [{name:"siva"}, {name:"siva1"}] ;
b = myCopy(a)
b === a // false`
I myself landed on these answers last day, trying to find a way to deep copy complex structures, which may include recursive links. As I wasn't satisfied with anything being suggested before, I implemented this wheel myself. And it works quite well. Hope it helps someone.
Example usage:
OriginalStruct.deep_copy = deep_copy; // attach the function as a method
TheClone = OriginalStruct.deep_copy();
Please look at https://github.com/latitov/JS_DeepCopy for live examples how to use it, and also deep_print() is there.
If you need it quick, right here's the source of deep_copy() function:
function deep_copy() {
'use strict'; // required for undef test of 'this' below
// Copyright (c) 2019, Leonid Titov, Mentions Highly Appreciated.
var id_cnt = 1;
var all_old_objects = {};
var all_new_objects = {};
var root_obj = this;
if (root_obj === undefined) {
console.log(`deep_copy() error: wrong call context`);
return;
}
var new_obj = copy_obj(root_obj);
for (var id in all_old_objects) {
delete all_old_objects[id].__temp_id;
}
return new_obj;
//
function copy_obj(o) {
var new_obj = {};
if (o.__temp_id === undefined) {
o.__temp_id = id_cnt;
all_old_objects[id_cnt] = o;
all_new_objects[id_cnt] = new_obj;
id_cnt ++;
for (var prop in o) {
if (o[prop] instanceof Array) {
new_obj[prop] = copy_array(o[prop]);
}
else if (o[prop] instanceof Object) {
new_obj[prop] = copy_obj(o[prop]);
}
else if (prop === '__temp_id') {
continue;
}
else {
new_obj[prop] = o[prop];
}
}
}
else {
new_obj = all_new_objects[o.__temp_id];
}
return new_obj;
}
function copy_array(a) {
var new_array = [];
if (a.__temp_id === undefined) {
a.__temp_id = id_cnt;
all_old_objects[id_cnt] = a;
all_new_objects[id_cnt] = new_array;
id_cnt ++;
a.forEach((v,i) => {
if (v instanceof Array) {
new_array[i] = copy_array(v);
}
else if (v instanceof Object) {
new_array[i] = copy_object(v);
}
else {
new_array[i] = v;
}
});
}
else {
new_array = all_new_objects[a.__temp_id];
}
return new_array;
}
}
Cheers#!
I would suggest using the spread operator. You'll need to spread a second time if you need to update the second level. Attempting to update the newObject using something like newObject.address.city will throw an error if address did not already exist in oldObject.
const oldObject = {
name: 'A',
address: {
street: 'Station Road',
city: 'Pune'
}
}
const newObject = {
...oldObject,
address: {
...oldObject.address,
city: 'Delhi'
}
}
console.log(newObject)
This is a very old question but I think in 2022 there are many ways to solve this. However, if you want a simple, fast and vanilla JS solution check this out:
const cloner = (o) => {
let idx = 1
const isArray = (a) => a instanceof Array
const isObject = (o) => o instanceof Object
const isUndefined = (a) => a === undefined
const process = v => {
if (isArray(v)) return cloneArray(v)
else if (isObject(v)) return cloneObject(v)
else return v
}
const register = (old, o) => {
old.__idx = idx
oldObjects[idx] = old
newObjects[idx] = o
idx++
}
const cloneObject = o => {
if (!isUndefined(o.__idx)) return newObjects[o.__idx]
const obj = {}
for (const prop in o) {
if (prop === '__idx') continue
obj[prop] = process(o[prop])
}
register(o, obj)
return obj
}
const cloneArray = a => {
if (!isUndefined(a.__idx)) return newObjects[a.__idx]
const arr = a.map((v) => process(v))
register(a, arr)
return arr
}
const oldObjects = {}
const newObjects = {}
let tmp
if (isArray(o)) tmp = cloneArray(o)
else if (isObject(o)) tmp = cloneObject(o)
else return o
for (const id in oldObjects) delete oldObjects[id].__idx
return tmp
}
const c = {
id: 123,
label: "Lala",
values: ['char', 1, {flag: true}, [1,2,3,4,5], ['a', 'b']],
name: undefined
}
const d = cloner(c)
d.name = "Super"
d.values[2].flag = false
d.values[3] = [6,7,8]
console.log({ c, d })
It's recursive and self-contained, all the functions needed are defined in the function cloner().
In this snippet we are handling Array and Object types if you want to add more handlers you can add specify handlers like Date and clone it like new Date(v.getTime())
For me Array and Object are the types that I use the most in my implementations.
doc = {
'a': {
'b': {
'c': 'hello'
},
'd': {
'c': 'sup',
'e': {
'f': 'blah blah blah'
}
}
}
}
function get(json, path) {
var str = path.split('.');
var temp = json;
var arr = [];
var keystr = "";
for (var i = 0; i < str.length; i++) {
if (str[i] != "*") {
keystr += str[i] + ".";
if (temp[str[i]] === undefined)
break;
else {
temp = temp[str[i]];
if (i == str.length - 1) {
var nObj = {};
nObjKey = keystr.substr(0, keystr.length - 1);
nObj[nObjKey] = temp
// console.log("Obj check" + JSON.stringify(nObj) + keystr)
arr.push(nObj);
}
}
} else {
for (var key in temp) {
var concat = key + "."
for (var j = i + 1; j < str.length; j++)
concat += str[j] + ".";
if (temp[key] !== undefined && temp[key] instanceof Object) {
var m = keystr + concat.substr(0, concat.length - 1);
var obj = (get(temp, concat.substr(0, concat.length - 1)));
if (obj != "") {
// console.log("existing arr "+JSON.stringify(arr))
obj[m] = (obj[0])[concat.substr(0, concat.length - 1)]
// console.log("hello "+JSON.stringify(obj) + " end hello")
arr.push(obj);
}
} else if (temp[key] !== undefined && i == str.length - 1) {
// arr.push(temp);
}
}
}
}
return arr;
}
var result = (get(doc, 'a.*.e'))
console.log(result)
For input of 'a.*.e' the output should be {'a.d.e': {'f': 'blah blah blah'}}}. But I get all the replacement for wild card as well in the array. I am sure something is wrong but not able to detect it. Help would be appreciated.
You could change the structure of the operation a little bit with a recursive approach and an exit early exit often paradigm with checking of single parts with exit options, like
length, a part result is found,
falsy or not object types,
part at index is a star, then iterate all keys from the object, or
the part at index is a key, then call the function again.
At the end, with a found path, joint the path and generate a new property with the actual value of the object.
function get(object, path) {
function iter(o, p, i) {
if (i === parts.length) {
result[p.join('.')] = o;
return;
}
if (!o || typeof o !== 'object') {
return;
}
if (parts[i] === '*') {
Object.keys(o).forEach(function (k) {
iter(o[k], p.concat(k), i + 1);
});
return;
}
if (parts[i] in o) {
iter(o[parts[i]], p.concat(parts[i]), i + 1);
}
}
var result = {},
parts = path.split('.');
iter(object, [], 0);
return result;
}
var doc = { a: { b: { c: 'hello' }, d: { c: 'sup', e: { f: 'blah blah blah' } } } };
console.log(get(doc, 'a.*.e'));
console.log(get(doc, 'a.*.c'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Version with * as wildcard for any level.
function get(object, path) {
function iter(o, p, i) {
if (i === parts.length) {
result[p.join('.')] = o;
return;
}
if (!o || typeof o !== 'object') {
return;
}
if (parts[i] === '*') {
Object.keys(o).forEach(function (k) {
iter(o[k], p.concat(k), i);
iter(o[k], p.concat(k), i + 1);
});
return;
}
if (parts[i] in o) {
iter(o[parts[i]], p.concat(parts[i]), i + 1);
}
}
var result = {},
parts = path.split('.');
iter(object, [], 0);
return result;
}
var doc = { a: { b: { c: 'hello' }, d: { c: 'sup', e: { f: 'blah blah blah' } } } };
console.log(get(doc, 'a.*.e'));
console.log(get(doc, 'a.*.c'));
console.log(get(doc, 'a.*.f'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
First of all, since your desired output {'a.d.e': {'f': 'blah blah blah'}}} does not contain any array, but only plain objects, you should not need the variable arr in your code.
Instead, return nObj as function result, and declare it at the start, never clearing it.
Secondly, when you come back from the recursive call, the results need to be copied while prefixing the paths with what you already had. Note that checking for an empty array should not be done with != "", but anyway, you don't need that any more.
You could write this from scratch in different ways (see solution at end of answer), but I have first adapted your code to only change the bare minimum, with comments where I made the changes to make it work:
function get(json, path) {
var str = path.split('.');
var temp = json;
var arr = [];
var keystr = "";
// *** Define here the object to return
var nObj = {};
for (var i = 0; i < str.length; i++) {
if (str[i] != "*") {
keystr += str[i] + ".";
if (temp[str[i]] === undefined)
break;
else {
temp = temp[str[i]];
if (i == str.length - 1) {
// *** Move this to start of the function
//var nObj = {};
nObjKey = keystr.substr(0, keystr.length - 1);
nObj[nObjKey] = temp
}
}
} else {
for (var key in temp) {
var concat = key + "."
for (var j = i + 1; j < str.length; j++)
concat += str[j] + ".";
if (temp[key] !== undefined && temp[key] instanceof Object) {
var m = keystr + concat.substr(0, concat.length - 1);
var obj = get(temp, concat.substr(0, concat.length - 1));
// *** Return value is object with path(s) as keys
// *** Don't compare array with string
//if (arr != "") {
// *** Iterate over the returned object properties, and prefix them
for (var deepKey in obj) {
nObj[keystr + deepKey] = obj[deepKey];
}
//*** No need for array; we already have the object properties
//arr.push(obj);
//}
// *** No need for array
//} else if (temp[key] !== undefined && i == str.length - 1) {
// arr.push(temp);
}
}
}
}
// *** Return object
return nObj;
}
var doc = {
'a': {
'b': {
'c': 'hello'
},
'd': {
'c': 'sup',
'e': {
'f': 'blah blah blah'
},
},
'g': {
'e': {
'also': 1
}
}
}
}
var result = (get(doc, 'a.*.e'));
console.log(result);
Please also consider not name objects json when they are not: JSON is a text format, JavaScript object variables are not the same thing as JSON.
Compact ES6 solution
When you are used to array functions like reduce and a functional programming style, the following compact ES6 solution might appeal to you:
function get(obj, path) {
if (typeof path === 'string') path = path.split('.');
return !path.length ? { '': obj } // Match
: obj !== Object(obj) ? {} // No match
: (path[0] === '*' ? Object.keys(obj) : [path[0]]) // Candidates
.reduce( (acc, key) => {
const match = get(obj[key], path.slice(1)); // Recurse
return Object.assign(acc, ...Object.keys(match).map( dotKey =>
({ [key + (dotKey ? '.' + dotKey : '')]: match[dotKey] })
));
}, {});
}
const doc = {
'a': {
'b': {
'c': 'hello'
},
'd': {
'c': 'sup',
'e': {
'f': 'blah blah blah'
},
},
'g': {
'e': {
'also': 1
}
}
}
};
const result = get(doc, 'a.*.e');
console.log(result);
List monad
Here's a solution which borrows ideas from the List monad to represent a computation which may have 0, 1, or more results. I'm not going to cover it in detail and I've only included enough of the List type to get a working solution. If you're interested in this sort of approach, you can do some more research on the topic or ask me a follow-up question.
I'm also using an auxiliary find function which is the recursive helper for get which operates the array of keys that get prepares
If you like this solution, I've written about the list monad in some other answers; you might find them helpful ^_^
const List = xs =>
({
value:
xs,
bind: f =>
List (xs.reduce ((acc, x) =>
acc.concat (f (x) .value), []))
})
const find = (path, [key, ...keys], data) =>
{
if (key === undefined)
return List([{ [path.join('.')]: data }])
else if (key === '*')
return List (Object.keys (data)) .bind (k =>
find ([...path, k], keys, data[k]))
else if (data[key] === undefined)
return List ([])
else
return find ([...path, key], keys, data[key])
}
const get = (path, doc) =>
find ([], path.split ('.'), doc) .value
const doc =
{a: {b: {c: 'hello'},d: {c: 'sup',e: {f: 'blah blah blah'}}}}
console.log (get ('a.b.c', doc))
// [ { 'a.b.c': 'hello' } ]
console.log (get ('a.*.c', doc))
// [ { 'a.b.c': 'hello' }, { 'a.d.c': 'sup' } ]
console.log (get ('a.*', doc))
// [ { 'a.b': { c: 'hello' } },
// { 'a.d': { c: 'sup', e: { f: 'blah blah blah' } } } ]
console.log (get ('*.b', doc))
// [ { 'a.b': { c: 'hello' } } ]
Native arrays only
We don't have to do fancy List abstraction in order to achieve the same results. In this version of the code, I'll show you how to do it using nothing but native Arrays. The only disadvantage of this code is the '*'-key branch gets a little complicated by embedding the flatmap code inline with our function
const find = (path, [key, ...keys], data) =>
{
if (key === undefined)
return [{ [path.join ('.')]: data }]
else if (key === '*')
return Object.keys (data) .reduce ((acc, k) =>
acc.concat (find ([...path, k], keys, data[k])), [])
else if (data[key] === undefined)
return []
else
return find ([...path, key], keys, data[key])
}
const get = (path, doc) =>
find([], path.split('.'), doc)
const doc =
{a: {b: {c: 'hello'},d: {c: 'sup',e: {f: 'blah blah blah'}}}}
console.log (get ('a.b.c', doc))
// [ { 'a.b.c': 'hello' } ]
console.log (get ('a.*.c', doc))
// [ { 'a.b.c': 'hello' }, { 'a.d.c': 'sup' } ]
console.log (get ('a.*', doc))
// [ { 'a.b': { c: 'hello' } },
// { 'a.d': { c: 'sup', e: { f: 'blah blah blah' } } } ]
console.log (get ('*.b', doc))
// [ { 'a.b': { c: 'hello' } } ]
Why I recommend the List monad
I do personally recommend the List monad approach as it keeps the body of the find function most clean. It also encompasses the concept of ambiguous computation and allows you to reuse that wherever you might require such a behaviour. Without using the List monad, you would rewrite the necessary code each time which adds a lot of cognitive load on the understanding of the code.
Adjust the shape of your result
The return type of your function is pretty weird. We're returning an Array of objects that only have one key/value pair. The key is the path we found the data on, and the value is the matched data.
In general, we shouldn't be using Object keys this way. How would we display the results of our match?
// get ('a.*', doc) returns
let result =
[ { 'a.b': { c: 'hello' } },
{ 'a.d': { c: 'sup', e: { f: 'blah blah blah' } } } ]
result.forEach (match =>
Object.keys (match) .forEach (path =>
console.log ('path:', path, 'value:', match[path])))
// path: a.b value: { c: 'hello' }
// path: a.d value: { c: 'sup', e: { f: 'blah blah blah' } }
What if we returned [<key>, <value>] instead of {<key>: <value>}? It's much more comfortable to work with a result in this shape. Other reasons to support this is a better shape for your data is something like Array#entries or Map#entries()
// get ('a.*', doc) returns proposed
let result =
[ [ 'a.b', { c: 'hello' } ],
[ 'a.d', { c: 'sup', e: { f: 'blah blah blah' } } ] ]
for (let [path, value] of result)
console.log ('path:', path, 'value:', value)
// path: a.b value: { c: 'hello' }
// path: a.d value: { c: 'sup', e: { f: 'blah blah blah' } }
If you agree this is a better shape, updating the code is simple (changes in bold)
// List monad version
const find = (path, [key, ...keys], data) => {
if (key === undefined)
return List ([[path.join ('.'), data]])
...
}
// native arrays version
const find = (path, [key, ...keys], data) => {
if (key === undefined)
return [[path.join ('.'), data]]
...
}
I have an object similar to the one below:
var obj1 = {
fparams: {
keys: ['a', 'b'],
pairs: {
'p': 'qwert'
}
},
qparams: {
'x': 'xyz'
}
}
And another one as:
var obj2 = {
fparams: {
keys: ['c', 'd'],
pairs: {
'q': 'yuiop'
}
},
qparams: {
'z': 'zyx'
}
}
What can I do to add the properties from obj2 object to obj1?
As I am working in Angular, I tried to use angular.merge(obj1,obj2) but it does not merge the keys array, but overwrites it with the keys value from obj2, rest of the properties get merged though.
Here's what I want in the end:
var obj2 = {
fparams: {
keys: ['a', 'b', 'c', 'd'],
pairs: {
'p': 'qwert',
'q': 'yuiop'
}
},
qparams: {
'x': 'xyz',
'y': 'zyx'
}
}
Also The angular Version I'm Using Is angular 1.5.8
Edit : Ended up using lodash , as it was much easier to work with and tons of functionalities which I was not previously aware of.
Did you consider using Lodash? It has a merge method that does exactly that.
I guess simply with pure JS and the help of the recursive function mergeObjects you can do as follows;
function mergeObjects(o1,o2){
return Object.keys(o1)
.reduce(function(r,k){
o1[k] = Array.isArray(o1[k]) ? o1[k].concat(o2[k])
: typeof o1[k] === "object" ? mergeObjects(o1[k],o2[k])
: (r = Object.assign({},o1,o2),o1[k]);
return r;
}, o1);
}
var objs = [{
fparams: {
keys : ['a', 'b'],
pairs: {
'p': 'qwert'
}
},
qparams: {
'x': 'xyz'
}
},
{
fparams: {
keys : ['c', 'd'],
pairs: {
'q': 'yuiop'
}
},
qparams: {
'z': 'zyx'
}
}],
result = objs.reduce(mergeObjects);
console.log(JSON.stringify(result,null,2));
With lodash you can use mergeWith and create desired result, so when value is array you need to concat values.
var obj1 = {"fparams":{"keys":["a","b"],"pairs":{"p":"qwert"}},"qparams":{"x":"xyz"}}
var obj2 = {"fparams":{"keys":["c","d"],"pairs":{"q":"yuiop"}},"qparams":{"z":"zyx"}}
var result = _.mergeWith(obj1, obj2, function(a, b) {
if(_.isArray(a)) return a.concat(b)
})
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Here is my attempt at deep merge, using recursion, not sure if it will work on all data structures.
var obj1 = {"fparams":{"keys":["a","b"],"pairs":{"p":"qwert"}},"qparams":{"x":"xyz"}}
var obj2 = {"fparams":{"keys":["c","d"],"pairs":{"q":"yuiop"}},"qparams":{"z":"zyx"}}
function merge(o1, o2) {
var result = {}
for (var i in o1) {
for (var j in o2) {
if (i == j && typeof o1[i] == 'object' && typeof o2[j] == 'object') {
if (Array.isArray(o1[i]) || Array.isArray(o2[j])) {
result[i] = Array.isArray(o1[i]) ? o1[i].concat(o2[j]) : o2[j].concat(o1[i])
} else {
result[i] = Object.assign(result[i] || {}, merge(o1[i], o2[j]))
}
}
if (typeof o1[i] != 'object' || typeof o2[j] != 'object') {
result[i] = o1[i]
result[j] = o2[j]
}
}
}
return result;
}
console.log(JSON.stringify(merge(obj1, obj2), 0, 4))
try this function, I have tried to cover most of the scenarios though it might not be as good as other libraries available
var merge = function(obj1, obj2) {
for (var key in obj2) {
if (obj2.hasOwnProperty(key)) {
if (obj1[key] == null) {
obj1[key] = obj2[key];
} else if (obj1[key] instanceof Array) {
if (obj2[key] instanceof Array) {
for (var i =0; i < obj2[key].length; i++){
if (obj1[key].indexOf(obj2[key]) === -1) {
obj1[key].push(obj2[key][i]);
}
}
}
} else if (obj1[key] instanceof Object && obj2[key] instanceof Object && obj1[key].constructor == Object && obj2[key] == Object) {
merge(obj1[key], obj2[key]);
}
}
}
}
You can use it as below
merge(obj1, obj2);
I want to implement a function that returns an array of property values if the value is primitive (non-object or array) and property name starts with prefix.
For example
var values = function (obj, prefix) { ... }
var testObj = {
'a': 1,
'ab': [
{
'c': 2,
'ac': true
}
]
};
As a result of values(testObj, 'a') function invocation I expect to get such array of primitives: [1, true].
Here is my try:
var values = function (obj, prefix) {
var res = [];
for (var i in obj) {
if (i.startsWith(prefix)) {
var v = obj[i];
if (typeof v === 'object') {
var r0 = arguments.callee(v, prefix);
res.push(r0);
} else {
res.push(v);
}
}
}
return res;
};
But it returns a wrong result: [1, []]. How can I fix it?
You could use a recursive approach for the values, you need.
function values(obj, prefix) {
var result = [];
Object.keys(obj).forEach(function (k) {
if (obj[k] !== null && typeof obj[k] === 'object') {
result = result.concat(values(obj[k], prefix));
} else if (k.startsWith(prefix)) {
result.push(obj[k]);
}
});
return result;
}
var testObj = { 'a': 1, 'ab': [{ 'c': 2, 'ac': true }] },
result = values(testObj, 'a');
console.log(result);
Following code works.
var testObj = {
'a': 1,
'ab': [
{
'c': 2,
'ac': true
}
]
};
var values = function (obj, prefix) {
var res = [];
if(Array.isArray(obj)){
for(var j in obj){
res = res.concat(arguments.callee(obj[j], prefix));
}
}
else if(typeof obj == "object") {
for (var i in obj) {
if (i.startsWith(prefix)) {
var v = obj[i];
if (typeof v === 'object') {
res = res.concat(arguments.callee(v, prefix));
} else {
res.push(v);
}
}
}
}
return res;
};
console.log(values(testObj, 'a'));
This might be what you are looking for;
var testObj = {
'a': 1,
'ab': [
{
'c': 2,
'ac': true
}
]
};
getValues = (o,x) => Object.keys(o)
.reduce((p,k) => p.concat(typeof o[k] === "object" ? getValues(o[k],x)
: k.indexOf(x) >= 0 ? o[k]
: [])
,[]);
console.log(getValues(testObj,"a"));
(My city energy is weak.)
Where the main problem is in the i.startsWith(prefix) condition. It avoids you to enter a object without property name including #prefix inside a array. For example:
{ a: 1, ab: [ /* 0: { 'c': 2, 'ac': true } */ ] }
As you see, the object in the array is ignored since its property name is 0, that's its index.
If you really want to get this result: [1, true] you'll have to skip the array and return the first item to res.push.
var values = function (obj, prefix) {
var res = [];
for (var i in obj) {
if (i.startsWith(prefix)) {
var v = obj[i];
if (typeof v === 'object') {
var isArray = v instanceof Array;
var r0 = arguments.callee(isArray ? v[0] : v, prefix);
res.push(isArray && r0.length === 1 ? r0[0] : r);
} else {
res.push(v);
}
}
}
return res;
};
var testObj = {
'a': 1,
'ab': [
{
'c': 2,
'ac': true
}
]
};
var res = [];
var values = function (obj, prefix) {
for (var i in obj) {
var v = obj[i];
//Prefix check line can be moved here if you want to check the prefix for object
if (typeof v === 'object') {
arguments.callee(v, prefix);
} else {
if (i.startsWith(prefix)) { //Prefix Check
res.push(v);
}
}
}
return res;
};
console.log(values(testObj,'a'));
Please check this, this gives the output that you wanted.
I'm using an object as a hash table. I'd like to quickly print out its contents (for alert() for instance). Is there anything built in to convert a hash into arrays of (key, value) pairs?
Since you want to alert it out I assume it's not for your production version, and that old browser compatibility is not an issue.
If this is the case, then you can do this:
var myHash = ......
alert(Object.keys(myHash).map(function(key) { return [key, myHash[key]]; }));
I updated this some more. This is much easier to parse than even console.log because it leaves out the extra stuff that's in there like __proto__.
function flatten(obj) {
var empty = true;
if (obj instanceof Array) {
str = '[';
empty = true;
for (var i=0;i<obj.length;i++) {
empty = false;
str += flatten(obj[i])+', ';
}
return (empty?str:str.slice(0,-2))+']';
} else if (obj instanceof Object) {
str = '{';
empty = true;
for (i in obj) {
empty = false;
str += i+'->'+flatten(obj[i])+', ';
}
return (empty?str:str.slice(0,-2))+'}';
} else {
return obj; // not an obj, don't stringify me
}
}
The only thing I would do to improve this is have it indent correctly based on recursion level.
for quick & dirty use in alert you could use JSON:
alert(JSON.stringify(yourObj).replace(/,/g,'\n'));
Not that I'm aware of. Still, you can do it yourself fairly concisely:
var obj = { a: 1, b: 2, c: 3 };
var arr = [];
for (var i in obj) {
var e = {};
e[i] = obj[i];
arr.push(e);
}
console.log(arr);
// Output: [Object { a=1 }, Object { b=2 }, Object { c=3 }]
Of course, you can't alert this either, so you might as well just console.log(obj) in the first place.
You could output arrays of arrays:
var obj = { a: 1, b: 2, c: 3 };
var arr = [];
for (var i in obj) {
arr.push([i, obj[i]]);
}
console.log(arr);
// Output: [["a", 1], ["b", 2], ["c", 3]]
alert(arr);
// Alert: a, 1, b, 2, c, 3
But, again, ew.
Here is my version of it. It should allow you to flatten input like below:
var input = {
a: 'asdf',
b: [1,2,3],
c: [[1,2],[3,4]],
d: {subA: [1,2]}
}
The function is like this:
function flatten (input, output) {
if (isArray(input)) {
for(var index = 0, length = input.length; index < length; index++){
flatten(input[index], output);
}
}
else if (isObject(input)) {
for(var item in input){
if(input.hasOwnProperty(item)){
flatten(input[item], output);
}
}
}
else {
return output.push(input);
}
};
function isArray(obj) {
return Array.isArray(obj) || obj.toString() === '[object Array]';
}
function isObject(obj) {
return obj === Object(obj);
}
Usage is something like:
var output = []
flatten(input, output);
Then output should be the flattened array.
Maybe a little late, but here you have my version of the answer, updated to ES2015. I use a recursive function and it works even if there are other objects inside the main object:
function objectFlattener (object) {
return Reflect.apply(Array.prototype.concat, [], Object.keys(object).map(key => {
if (object[key] instanceof Object) {
return objectFlattener(object[key]);
}
return `${ key }: ${ object[key] }`;
}));
}
So changing the last return you can format the element inside your array.
Use the for loop:
for (var x in yourObj)
{
alert(yourObj[x]);
}