Merging objects - javascript

I am trying to merge the objects recursively.
what I have
arrayOfObjects = [{a1:{aa:k1}},{a1:{ab:k2}},{a1:{ac:k3}},{a1:{aa:k4}},{a1:{ab:k5}}];
what I need is
{a1:{aa:k1,ab:k2,ac:k3,aa:k4,ab:k5}}
I made a function
function merg(array){
value = {};
if(array.length>0){
$.each(array, function (i) {
value = $.extend(true,{},value,array[i]);
});
}
return value;
};
console.log(merg(arrayOfObjects));
what I get is
{a1:{aa:k1,ab:k2,ac:k3}}
aa:k4,ab:k5 are missing(may due to same key value )
if the deep merge is false I get only one value
value = $.extend({},value,array[i]);
{a1:{aa:k1}}

We can make use of Symbols,
var arr = [{a1:{aa:'k1'}},{a1:{ab:'k2'}},{a1:{ac:'k3'}},{a1:{aa:'k4'}},{a1:{ab:'k5'}}];;
var op = {};
var result = {};
var globalKey;
arr.forEach((ar) => {
var [key, value] = Object.entries(ar)[0];
globalKey = key;
var [innerKey, innerValue] = Object.entries(value)[0];
op[Symbol(innerKey)] = innerValue;
});
result[globalKey] = op;
console.log(result);

Related

How to use string as a key to update object

I am trying to create a function that accepts the path in an object and makes that the key.
for example, if I wanted to update the city, which is is a child object of a company, which is a child object of a property I could do something like this:
originalObj['property']['company']['city'] = test
Here is my code so far:
function updateObj(path, value){
let valuePath = path.split(',')
let key=''
for(let i=0; i<valuePath.length ; i++){
key = key+`[valuePath[${i}]]`
}
//key = [valuePath[0]] [valuePath[1]] [valuePath[2]]
originalObj[key] = value
}
setObj('property,company,city', test)
You could save the last key of the path and use a temporary object for getting the final object for assigning the value.
function updateObj(path, value) {
var valuePath = path.split(','),
last = valuePath.pop(),
temp = object;
for (let i = 0; i < valuePath.length; i++) {
temp = temp[valuePath[i]];
}
temp[last] = value;
}
var object = { property: { company: { city: 'London' } } };
updateObj('property,company,city', 'New York');
console.log(object);
With Array#reduce
function updateObj(path, value) {
var valuePath = path.split(','),
last = valuePath.pop();
valuePath.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var object = {};
updateObj('property,company,city', 'New York');
console.log(object);
function updateObj(obj, path, value){
path.split(",").slice(0,-1).reduce((obj, key) => obj[key] || (obj[key] = {}), obj)[path.split(",").pop()] = value;
}
Try this:
function setObj(originalObj, path, value){
var parts = path.split(',');
var lastKey = parts.pop();
var obj = originalObj;
parts.forEach(
function(key) {
key = key.trim();
obj[key] = obj[key] || {};
obj = obj[key];
}
);
obj[lastKey] = value;
}
var originalObj = {};
var test = "This is a test";
setObj(originalObj, 'property,company,city', test)
console.log(JSON.stringify(originalObj,0,2));
It walks through your list and creates sub objects for all but the last. It then uses the last as the key to store the value.
The advantage to this code is that you don't assume the original Object variable name. And, if you wanted it to be pure and not to affect the original object structure then you could make these minor changes:
function setObj(originalObj, path, value){
var parts = path.split(',');
var lastKey = parts.pop();
var newObj = Object.assign({}, originalObj);
var obj = newObj;
parts.forEach(
function(key) {
obj[key] = Object.assign({}, obj[key] || {});
obj = obj[key];
}
);
obj[lastKey] = value;
return newObj;
}
var originalObj = {animals: {dog:"bark",cat:"meow"},property:{company:{name:"Fred's Things"}}};
var test = "This is a test";
var result = setObj(originalObj, 'property,company,city', test)
console.log(JSON.stringify(originalObj,0,2));
console.log(JSON.stringify(result,0,2));

Dynamic object creation from an array

I want to generate a dynamic object and assign value into it. Following is the code
var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};
So the output should be like this
a["INTERNATIONALISATION"]["LANGUAGE"]["DICTIONARY"]["EN"] = 10;
Tried looping through array but nothing works for now.Please advise.
Try this:
var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};
var lastKey = c.pop();
c.reduce((obj, key) => obj[key] = obj[key] || {}, a)[lastKey] = 10;
To make it more convenient you can put it in a function:
const dynamicAssign = (object, stringPath, value) => {
const path = stringPath.split('#');
const lastKey = path.pop();
const target = path.reduce((obj, key) => obj[key] = obj[key] || {}, object);
target[lastKey] = value;
};
const a = {};
dynamicAssign(a, "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN", 10);

Remove duplicates from string using jquery?

How i Remove duplicates from my string
var string="1,2,3,2,4,5,4,5,6,7,6";
But i want like this
var string="1,2,3,4,5,6,7";
Yes you can do it easily, Here is the working example
data = "1,2,3,2,4,5,4,5,6,7,6";
arr = $.unique(data.split(','));
data = arr.join(",");
console.log(data);
Create the following prototype and use it to remove duplicates from any array.
Array.prototype.unique = function () {
var arrVal = this;
var uniqueArr = [];
for (var i = arrVal.length; i--; ) {
var val = arrVal[i];
if ($.inArray(val, uniqueArr) === -1) {
uniqueArr.unshift(val);
}
}
return uniqueArr;
}
Ex:
var str = "1,6,7,7,8,9";
var array1 = str.split(',');
var array1 = array1.unique();
console.log(array1); // [1,6,7,8,9]
str = array1.join();
Use the following to push unique values into a new array.
var names = [1,2,2,3,4,5,6];
var newNames = [];
$.each(names, function(index, value) {
if($.inArray(value, newNames) === -1)
newNames.push(value);
});

Get the index of a multidimensional array with the value of a given string in javascript

I have this array,
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
And I want to get the data[0] of the array that have value of "Mary".
So in my example, value that I will get is "absent".
I want also to get the index of the array arr2 that have value of "Josh".
So in my second array, value that I will get is 0.
If possible to use underscore js, we can use it.
I tried to use _.contains() but failed.
Also these array is used in knockout js.
One other way of doing this job could be as follows;
var a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
getIndex = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
console.log(getStatus(a1,"Mary"));
console.log(getIndex(a2,"Sammy Davis"));
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
arr.forEach(function(e,i,a){
if(e[1].indexOf("Mary")>-1){
console.log(e[0])
}
});
arr2.forEach(function(e,i,a){
if(e[1].indexOf("Josh")>-1){
console.log(e[0])
}
});
First using filter() and second findIndex()
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var result1 = arr.filter(x => x[1].indexOf("Mary") !== -1)[0][0];
console.log(result1); // absent
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
var result2 = arr.findIndex(x => x[1].indexOf("Josh") !== -1);
console.log(result2); // 0
If your data set isn't really huge you can store two map objects in memory to quickly access values. Note that this won't work for duplicate names.
The benefit of this approach is that you only have to loop through each array once. If you use any method based on indexOf, you'll loop through your data every time you retrieve a value.
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
var makeKeyMap = function(arr) {
return arr.reduce(function(map, data) {
data[1].forEach(function(key) {
map[key] = data[0];
});
return map;
}, {});
};
var makeIndexMap = function(arr) {
return arr.reduce(function(map, data, index) {
data[1].forEach(function(key) {
map[key] = index;
});
return map;
}, {});
};
var arrMap = makeKeyMap(arr);
var arr2Map = makeIndexMap(arr2);
console.log(arrMap["Mary"]);
console.log(arr2Map["Josh"]);
Edit: a performance test
var myTestData = createTestData();
var randomNameToFind = (function() {
var namesToFind = ["Aileen","Christina","Donna","Judith","Mandy","Sandra","Dawn","Tracey","Mhairi","Victoria","Carolyn","Gayle","Maria","Valerie"];
return function() {
return namesToFind[Math.floor(Math.random() * namesToFind.length)];
}
}());
console.log("Finding the number index for a random name out of 800 names, 10000 times:");
console.time("using index of approach");
var usingIndexOf = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
var results = [];
for (var i = 0; i < 10000; i += 1) {
results.push(usingIndexOf(myTestData, randomNameToFind()));
}
console.timeEnd("using index of approach");
console.time("using map approach");
var makeIndexMap = function(arr) {
return arr.reduce(function(map, data, index) {
data[1].forEach(function(key) {
map[key] = index;
});
return map;
}, {});
};
var myMap = makeIndexMap(myTestData);
results = [];
for (var j = 0; j < 10000; j += 1) {
results.push(myMap[randomNameToFind()]);
}
console.timeEnd("using map approach");
console.log("index map size: " + sizeof(myMap) + " bytes");
// Random data generation code below
function createTestData() {
var names = ["Nicola","Karen","Fiona","Susan","Claire","Sharon","Angela","Gillian","Julie","Michelle","Jacqueline","Amanda","Tracy","Louise","Jennifer","Alison","Sarah","Donna","Caroline","Elaine","Lynn","Margaret","Elizabeth","Lesley","Deborah","Pauline","Lorraine","Laura","Lisa","Tracey","Carol","Linda","Lorna","Catherine","Wendy","Lynne","Yvonne","Pamela","Kirsty","Jane","Emma","Joanne","Heather","Suzanne","Anne","Diane","Helen","Victoria","Dawn","Mary","Samantha","Marie","Kerry","Ann","Hazel","Christine","Gail","Andrea","Clare","Sandra","Shona","Kathleen","Paula","Shirley","Denise","Melanie","Patricia","Audrey","Ruth","Jill","Lee","Leigh","Catriona","Rachel","Morag","Kirsten","Kirsteen","Katrina","Joanna","Lynsey","Cheryl","Debbie","Maureen","Janet","Aileen","Arlene","Zoe","Lindsay","Stephanie","Judith","Mandy","Jillian","Mhairi","Barbara","Carolyn","Gayle","Maria","Valerie","Christina","Marion","Nicola","Karen","Susan","Claire","Fiona","Angela","Sharon","Gillian","Julie","Jennifer","Michelle","Louise","Lisa","Amanda","Donna","Tracy","Alison","Elaine","Jacqueline","Sarah","Caroline","Elizabeth","Laura","Lynn","Deborah","Lesley","Margaret","Joanne","Pauline","Lorraine","Carol","Kirsty","Yvonne","Lorna","Emma","Lynne","Tracey","Heather","Catherine","Pamela","Helen","Linda","Jane","Anne","Kerry","Suzanne","Wendy","Victoria","Diane","Mary","Dawn","Clare","Gail","Paula","Ann","Shona","Hazel","Christine","Andrea","Samantha","Marie","Lynsey","Sandra","Denise","Lee","Kelly","Gayle","Debbie","Jill","Kathleen","Patricia","Joanna","Catriona","Shirley","Ruth","Zoe","Leigh","Rachel","Melanie","Kirsteen","Aileen","Christina","Janet","Katrina","Stephanie","Audrey","Kirsten","Arlene","Maureen","Morag","Marion","Mhairi","Allison","Cheryl","Maria","Kim","Anna","Lindsay","Rebecca","Katherine","Mandy","Nicola","Karen","Claire","Angela","Fiona","Susan","Jennifer","Julie","Gillian","Michelle","Sharon","Sarah","Louise","Donna","Laura","Amanda","Alison","Lisa","Caroline","Kirsty","Jacqueline","Elaine","Lesley","Lynn","Deborah","Elizabeth","Joanne","Emma","Tracy","Lorraine","Lynne","Margaret","Heather","Carol","Lorna","Pauline","Kelly","Helen","Catherine","Linda","Victoria","Suzanne","Kerry","Pamela","Lee","Wendy","Jane","Yvonne","Tracey","Anne","Clare","Mary","Diane","Christine","Lynsey","Samantha","Shona","Andrea","Marie","Gail","Melanie","Dawn","Ann","Paula","Jill","Ruth","Leigh","Hazel","Debbie","Joanna","Denise","Lindsay","Gayle","Patricia","Catriona","Kathleen","Sandra","Leanne","Stephanie","Rachel","Katrina","Shirley","Kirsteen","Janet","Arlene","Zoe","Jillian","Anna","Judith","Mhairi","Natalie","Audrey","Carolyn","Morag","Aileen","Cheryl","Rebecca","Allison","Barbara","Mandy","Claire","Nicola","Karen","Angela","Gillian","Fiona","Jennifer","Laura","Susan","Julie","Michelle","Lisa","Sharon","Louise","Sarah","Tracy","Donna","Kelly","Kirsty","Amanda","Alison","Joanne","Caroline","Emma","Jacqueline","Elaine","Elizabeth","Lynne","Lesley","Deborah","Kerry","Victoria","Carol","Catherine","Lynn","Pauline","Margaret","Lorna","Lynsey","Lorraine","Linda","Suzanne","Tracey","Heather","Yvonne","Jane","Dawn","Mary","Helen","Anne","Wendy","Lee","Pamela","Jill","Lindsay","Clare","Christine","Diane","Leigh","Samantha","Shona","Joanna","Ruth","Debbie","Gail","Marie","Andrea","Paula","Kathleen","Catriona","Katrina","Denise","Melanie","Ann","Sandra","Gayle","Hazel","Jillian","Stephanie","Rachel","Kim","Natalie","Katherine","Patricia","Leanne","Cheryl","Mhairi","Morag","Arlene","Zoe","Kathryn","Aileen","Ashley","Judith","Anna","Frances","Janet","Lucy","Vicky","Christina","Kirsten","Rebecca","Nicola","Claire","Laura","Karen","Michelle","Louise","Jennifer","Fiona","Lisa","Gillian","Angela","Julie","Susan","Sarah","Kelly","Donna","Sharon","Emma","Caroline","Alison","Joanne","Tracy","Kirsty","Lynne","Amanda","Elaine","Jacqueline","Lesley","Kerry","Elizabeth","Lynn","Margaret","Deborah","Catherine","Heather","Lorna","Yvonne","Carol","Lorraine","Suzanne","Lynsey","Victoria","Helen","Linda","Pauline","Dawn","Anne","Jane","Tracey","Clare","Mary","Diane","Jill","Denise","Lee","Leanne","Christine","Shona","Pamela","Samantha","Paula","Joanna","Debbie","Stacey","Hazel","Cheryl","Lindsay","Gail","Rachel","Marie","Ann","Catriona","Andrea","Ruth","Kathryn","Katrina","Mhairi","Wendy","Leigh","Gayle","Melanie","Sandra","Stephanie","Anna","Jillian","Amy","Carolyn","Patricia","Carrie","Natalie","Kathleen","Lyndsey","Ashley","Rebecca","Vicky","Christina","Lindsey","Katherine","Arlene","Sara","Laura","Claire","Nicola","Lisa","Louise","Michelle","Fiona","Karen","Gillian","Jennifer","Emma","Angela","Susan","Kelly","Julie","Donna","Sarah","Kirsty","Sharon","Joanne","Amanda","Tracy","Alison","Elizabeth","Caroline","Elaine","Jacqueline","Lynne","Leanne","Deborah","Lesley","Lorraine","Victoria","Lynn","Pamela","Kerry","Lynsey","Lorna","Carol","Margaret","Heather","Helen","Catherine","Suzanne","Tracey","Yvonne","Cheryl","Linda","Pauline","Debbie","Jane","Dawn","Clare","Lindsay","Mary","Shona","Anne","Rachel","Jill","Christine","Natalie","Samantha","Diane","Lee","Wendy","Joanna","Paula","Marie","Ann","Denise","Catriona","Gayle","Hazel","Kathleen","Stacey","Gail","Ashley","Andrea","Ruth","Anna","Jillian","Leigh","Katrina","Stephanie","Mhairi","Katherine","Sandra","Lyndsey","Christina","Lucy","Patricia","Carrie","Rebecca","Kathryn","Lyndsay","Melanie","Amy","Sara","Arlene","Kirsten","Laura","Claire","Lisa","Nicola","Louise","Karen","Fiona","Jennifer","Michelle","Emma","Sarah","Gillian","Kelly","Susan","Angela","Donna","Kirsty","Julie","Pamela","Joanne","Caroline","Amanda","Tracy","Sharon","Lynne","Elaine","Deborah","Jacqueline","Alison","Lynsey","Victoria","Kerry","Leanne","Lorraine","Lesley","Elizabeth","Lorna","Catherine","Lynn","Suzanne","Heather","Helen","Lindsay","Margaret","Clare","Cheryl","Debbie","Pauline","Dawn","Carol","Mary","Natalie","Linda","Jane","Diane","Stacey","Carrie","Yvonne","Rebecca","Christine","Marie","Charlene","Rachel","Anne","Tracey","Jill","Samantha","Ashley","Paula","Joanna","Stephanie","Andrea","Shona","Denise","Anna","Hazel","Katrina","Ruth","Gayle","Lee","Sara","Catriona","Kathryn","Leigh","Mhairi","Wendy","Amy","Jillian","Katherine","Gail","Linsey","Christina","Lucy","Melanie","Sandra","Ann","Kathleen","Shelley","Kirsten","Kim","Lyndsey","Laura","Claire","Lisa","Nicola","Emma","Louise","Jennifer","Michelle","Sarah","Fiona","Karen","Gillian","Kirsty","Donna","Kelly","Pamela","Susan","Julie","Angela","Amanda","Lynsey","Sharon","Lynne","Deborah","Joanne","Victoria","Caroline","Alison","Leanne","Gemma","Elaine","Jacqueline","Lesley","Elizabeth","Lorraine","Kerry","Heather","Debbie","Catherine","Lynn","Lorna","Tracy","Suzanne","Yvonne","Cheryl","Natalie","Margaret","Lindsay","Diane","Helen","Pauline","Ashley","Rachel","Clare","Carol","Christine","Linda","Dawn","Rebecca","Stephanie","Jill","Tracey","Jane","Stacey","Paula","Shona","Anna","Charlene","Anne","Marie","Catriona","Samantha","Joanna","Ruth","Andrea","Mary","Denise","Kim","Mhairi","Hazel","Lauren","Amy","Kathryn","Carrie","Lyndsey","Lucy","Gail","Katherine","Christina","Linsey","Wendy","Katrina","Kimberley","Ann","Lee"];
var nameMap = names.reduce((map, n) => {
map[n[0]] = map[n[0]] || [];
map[n[0]].push(n);
return map;
}, {});
var testData = Object.keys(nameMap)
.sort()
.reduce((res, k) => {
res.push([k, nameMap[k]]);
return res;
}, []);
return testData;
};
<script src="http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/sizeof.compressed.js"></script>

convert array to object javascript

I have the following array:
["recordList", "userList", "lastChanged"]
And I want something like this:
lastChangedValue = "231231443234";
var object = {};
object = {
recordList: {
userList: {
lastChanged: lastChangedValue
}
}
}
How I can do this?
Thanks in advance.
Try this:
var array = ["recordList", "userList", "lastChanged"];
var value = "231231443234";
function arrayToObject(array, object, value) {
var ref = object;
for (var i=0; i<array.length-1; ++i) {
if (!ref[array[i]]) {
ref[array[i]] = {};
}
ref = ref[array[i]]
}
ref[array[array.length-1]] = value;
return object;
}
alert(JSON.stringify(arrayToObject(array, {}, value)));
You can iterate through property names and create one nested level of new object in each iteration:
var props = ["recordList", "userList", "lastChanged"];
var lastChangedValue = "231231443234";
var obj = {}
var nested = obj;
props.forEach(function(o, i) {
nested[o] = i === props.length - 1 ? lastChangedValue : {};
nested = nested[o];
});
console.log(obj);
There are probably a bunch of ways to do it, one way is with reduce
var keys = ["recordList", "userList", "lastChanged"];
var temp = keys.slice().reverse(),
lastChangedValue = "231231443234";
var result = temp.reduce( function (obj, val, ind, arr) {
if (ind===0) {
obj[val] = lastChangedValue;
return obj;
} else {
var x = {};
x[val] = obj;
return x;
}
}, {});
console.log(result);
Solving with recursion
var fields = ["recordList", "userList", "lastChanged"];
lastChangedValue = "231231443234";
var object = {};
(function addFields(o, i, v) {
if (i == fields.length - 1) {
o[fields[i]] = v;
return;
}
o[fields[i]] = {};
addFields(o[fields[i]], ++i, v)
})(object, 0, lastChangedValue);
alert(JSON.stringify(object));

Categories

Resources