how to merge two objects in javascript [duplicate] - javascript
This question already has an answer here:
How to merge objects using javascript
(1 answer)
Closed 8 years ago.
I would like to merge objects here and would like to convert to JSON object. I would like to create an object array and add objects in to it. In this example i would like to create ConsData object array and add each dataset in to it.
I would like the data to be like
[
{
"name":"aaa_aaaurf",
"region":"F&R",
"checkins":[[1,0],[2,0],[3,0],[4,3],[5,0],[6,0],[7,0],[8,3],[9,0],[10,0],[11,0],[12,0]],
"teamsize":[[1,0],[2,0],[3,0],[4,3],[5,0],[6,0],[7,0],[8,1],[9,0],[10,0],[11,0],[12,0]],
"Checkintimes":[[1,0],[2,0],[3,0],[4,184],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0]]
},
{
"name":"aaa_accessservices",
"region":"F&R",
"checkins":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,27],[12,12]],
"teamsize":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,11],[12,11]],
"Checkintimes":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,10],[12,12]]
}]
var ConsData = {};
var MergeData = {};
for(var x=0;x<dataset.length;x++)
{
repository = dataset[x].repository;
sbu = dataset[x].BusinessUnit
checkinsarray.push([index, dataset[x].AvgCheckinCount]);
teamsizearray.push([index, dataset[x].TeamSize]);
checkintimesarray.push([index, dataset[x].MeanBuildTimeHrs]);
ConsData["name"] = repository;
ConsData["region"] = sbu;
ConsData["checkins"] = checkinsarray;
ConsData["teamsize"] = teamsizearray;
ConsData["Checkintimes"] = checkintimesarray;
}
following is the data contained in dataset(fetched from csv file):
repository,month,year,MeanBuildTimeHrs,AvgCheckinCount,TeamSize,BusinessUnit
aaa_aaaurf,1,2013,0,0,0,Financial&Risk
aaa_aaaurf,2,2013,0,0,0,Financial&Risk
aaa_aaaurf,3,2013,0,0,0,Financial&Risk
aaa_aaaurf,4,2013,184,3,3,Financial&Risk
aaa_aaaurf,5,2013,0,0,0,Financial&Risk
aaa_aaaurf,6,2013,0,0,0,Financial&Risk
aaa_aaaurf,7,2013,0,0,0,Financial&Risk
aaa_aaaurf,8,2013,0,3,1,Financial&Risk
aaa_aaaurf,9,2013,0,0,0,Financial&Risk
aaa_aaaurf,10,2013,0,0,0,Financial&Risk
aaa_aaaurf,11,2013,0,0,0,Financial&Risk
aaa_aaaurf,12,2013,0,0,0,Financial&Risk
cCG_tzz,1,2013,5,3,100,Financial&Risk
cCG_tzz,2,2013,8,5,80,Financial&Risk
aCG_txz,1,2013,12,3,70,Financial&Risk
GCG_txz,1,2013,21,3,50,Financial&Risk
GCG_txz,2,2013,12,3,70,Financial&Risk
var dataArray = [], i;
for(i = 0; i < dataset.length; i++)
{
dataArray.push({
"name": dataset[x].repository,
"region": dataset[x].BusinessUnit,
"checkins": [index, dataset[x].AvgCheckinCount],
"teamsize": [index, dataset[x].TeamSize],
"Checkintimes": [index, dataset[x].MeanBuildTimeHrs]
});
}
console.log(JSON.stringify(dataArray));
You need to use a new object for every element in your array. Objects are stored by reference, and variables have function scope.
After having a look at your other questions, I recommend you to have a look at the JavaScript guide.
Can you use lodash?
var names = {
'characters': [
{ 'name': 'barney' },
{ 'name': 'fred' }
]
};
var ages = {
'characters': [
{ 'age': 36 },
{ 'age': 40 }
]
};
_.merge(names, ages);
// → { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
var food = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var otherFood = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.merge(food, otherFood, function(a, b) {
return _.isArray(a) ? a.concat(b) : undefined;
});
// → { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
Related
Best way to convert array to object [duplicate]
This question already has answers here: How to convert an array into an object in javascript with mapped key-value pairs? (4 answers) Closed 10 months ago. What is the best way to convert this const items = [ { name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" } ]; into this using javascript : const result = { Leon: "../poeple", Bmw: "../car" };
You could just reduce the array: const items = [{ name: "Leon", url: "../people" }, { name: "Bmw", url: "../car" } ]; const o = items.reduce((o, el) => { o[el.name] = el.url; return o; }, {}); console.log(o) The Array.prototype.reduce method is very flexible, and might be used to reduce an array to another entity: The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You could map the objects as entries and get an object from it. const items = [{ name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" }], result = Object.fromEntries(items.map(({ name, url }) => [name, url])); console.log(result);
There are lots of different approaches as your can see. But if you're new to JavaScript maybe a simple loop over the array to create new keys and values in a new object would be easier to understand. const items=[{name:"Leon",url:"../poeple"},{name:"Bmw",url:"../car"}]; const out = {}; for (const obj of items) { out[obj.name] = obj.url; } console.log(out);
Another way (tested on your example): function convertit (src) { var dest = {}, i; for (i = 0; i < src.length; i++) { var record = src[i]; dest[record.name] = record.url; } return dest; }
Try Like This const items = [ { name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" } ]; const newObj = Object.fromEntries(items.map(ele => [ele.name,ele.url])); console.log(newObj); Or You can create function like this const items = [ { name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" } ]; const convertArrayToObject = (array, key) => { const initialValue = {}; return array.reduce((obj, item) => { return { ...obj, [item[key]]: item.url, }; }, initialValue); }; console.log(convertArrayToObject(items, "name"));
Is there a method to split an array of objects into groups?
Suppose I have an array of objects with some sort of groupable key: var people = [ { 'name':'Alice', 'gender': 'female' }, { 'name':'Bob', 'gender': 'male' }, { 'name':'Jeremy', 'gender': 'male' }, { 'name':'Jess', 'gender': 'female' }, { 'name':'Seymour', 'gender': 'female' }, ]; Is there a (native) function/method that can be applied to the array to 'unzip' the array into two arrays, like so: boysAndGirls = people.[**something**]('gender'); That could result in: { 'male': [ ... ], 'female': [ ... ] } or even: [ [ {Bob, ...}, {Jeremy, ...}, {Seymour, ...} ], // 'males' array [ {Alice, ...}, {Jess, ...} ] // 'female' array ] I could write this algorithm myself, but I really just want to know if there is a native array method -- or one that might exist in another language that could be polyfilled in?
const groupByAge = users.reduce((p,c) =>{ const genKey = Math.floor(c.age/10); const key = `${genKey}0- ${genKey}9`; if(!p[key]){ p[key] =[]; } p[key].push(c); return p; }, {}) console.log(groupByAge);
There is no such method in JavaScript. Ruby has it in Enumerator#group_by: people.group_by { |person| person['gender'] } and it is easy enough to write in JavaScript as well. In fact, some libraries have it already, e.g. Lodash. _.groupBy(people, function(person) { return person['gender']; }); If you write it yourself, you can customise it a bit: function groupByProp(array, prop) { var result = {}; array.forEach(function(item) { var val = item[prop]; if (!result[val]) result[val] = [item]; else result[val].push(item); }); return result; } groupByProp(people, 'gender');
There is not a native Javascript function for this but you can use the following code: var originalArray = [1,2,3,4,5,6,7,8,9]; var splitArray = function (arr, size) { var arr2 = arr.slice(0), arrays = []; while (arr2.length > 0) { arrays.push(arr2.splice(0, size)); } return arrays; } splitArrays = splitArray(originalArray, 2); console.log(splitArrays);
The nearest thing I can think of off the top of my head for a native solution is to use reduce. It's not as simple as what you are looking for but it works: var boysAndGirls = people.reduce(function(obj, item) { obj[item.gender].push(item.name); return obj; }, {male: [], female: []});
Turning an array into an array of objects with Underscore.js?
I have an array: var countries = ['Austria', 'America', 'Australia']; I know you can turn that into an object with Underscore.js like this: _.object(['name', 'name2', 'name3'], countries)); How can I turn the array into an array of objects that looks like this? var countriesObject = [ { name: 'Austria' }, { name: 'America' }, { name: 'Australia' } ]; (with all the keys named name).
No need to use Underscore.js for that. You can do it with plain javascript: var new_arr = []; countries.forEach(function(country) { var new_obj = {}; new_obj.name = country; new_arr.push(new_obj); }); console.table(new_arr);
var countriesObject = _.map (countries,function (country){ return { name: country } }
How do I convert a javascript object array to a string array of the object attribute I want? [duplicate]
This question already has answers here: Closed 10 years ago. Possible Duplicate: Accessing properties of an array of objects Given: [{ 'id':1, 'name':'john' },{ 'id':2, 'name':'jane' }........,{ 'id':2000, 'name':'zack' }] What's the best way to get: ['john', 'jane', ...... 'zack'] Must I loop through and push item.name to another array, or is there a simple function to do it?
If your array of objects is items, you can do: var items = [{ id: 1, name: 'john' }, { id: 2, name: 'jane' }, { id: 2000, name: 'zack' }]; var names = items.map(function(item) { return item['name']; }); console.log(names); console.log(items); Documentation: map()
Use the map() function native on JavaScript arrays: var yourArray = [ { 'id':1, 'name':'john' },{ 'id':2, 'name':'jane' }........,{ 'id':2000, 'name':'zack' }]; var newArray = yourArray.map( function( el ){ return el.name; });
You can do this to only monitor own properties of the object: var arr = []; for (var key in p) { if (p.hasOwnProperty(key)) { arr.push(p[key]); } }
You can use this function: function createStringArray(arr, prop) { var result = []; for (var i = 0; i < arr.length; i += 1) { result.push(arr[i][prop]); } return result; } Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.
Javascript: How convert array of objects to object with sorted unique arrays?
Have data that has this kind of structure: $input = [ { animal: 'cat', name: 'Rocky', value: 1 }, { animal: 'cat', name: 'Spot', value: 2 }, { animal: 'dog', name: 'Spot', value: 3 } ]; Need fastest possible method for converting to this format: $output = { animal: [ 'cat', 'dog' ], name: [ 'Rocky', 'Spot' ], value: [ 1, 2, 3 ] }; The output should have keys equal to each of the keys in each object from the input. And the output values should be arrays with the sorted unique values. I found a few ways to do it using nested loops, but slower than I would like. With 30,000 elements to the input array with 8 keys for each of the objects, the best I have been able to do is 300ms in Chrome. Would like to get down to 100ms. Is there any faster method using a map or reduce?
Yet another way for modern browsers: $input.reduce(function(acc, obj) { Object.keys(obj).forEach(function(k) { acc[k] = (acc[k] || []).concat(obj[k]) }) return acc },{})
Here's one way. $input = [ { animal: 'cat', name: 'Rocky', value: 1 }, { animal: 'cat', name: 'Spot', value: 2 }, { animal: 'dog', name: 'Spot', value: 3 } ]; $output = {animal:{},name:{},value:{}}; $input.forEach(function(v,i) { $output.animal[v.animal] = 1; $output.name[v.name] = 1; $output.value[v.value] = 1; }); $output.animal = Object.keys($output.animal); $output.name = Object.keys($output.name); $output.value = Object.keys($output.value); It prevents having to test each Array every time. You can performance compare to see if it helps. live example: http://jsfiddle.net/TJVtj/1/ If you don't want to hardcode the keys, you can make the solution generic. var keys = Object.keys($input[0]), $output = {}; keys.forEach(function(v) { $output[v] = {}; }); $input.forEach(function(v) { keys.forEach(function(vv) { $output[vv][v[vv]] = 1; }); }); keys.forEach(function(v) { $output[v] = Object.keys($output[v]); }); live example: http://jsfiddle.net/TJVtj/2/ Warning. All the values will be strings since they're fetched as object keys.
function inArray(needle, haystack) { var length = haystack.length; for(var i = 0; i < length; i++) { if(haystack[i] == needle) return true; } return false; } Above function is used to check duplicates $output={}; for(i=0; i< $input.length; i++) { if(!$output.animal) $output.animal=[]; if(!$output.name) $output.name=[]; if(!$output.value) $output.value=[]; var ani=$input[i]; if(ani.animal && !inArray(ani.animal, $output.animal)) $output.animal.push(ani.animal); if(ani.name && !inArray(ani.name, $output.name)) $output.name.push(ani.name); if(ani.value) $output.value.push(ani.value); } DEMO.
// If you don't know the objects all have the same keys you need to look at each one- var output= {}, input= [{ animal:'cat', name:'Rocky', value:1 },{ animal:'cat', name:'Spot', value:2 },{ animal:'dog', name:'Spot', value:3 }]; input.forEach(function(itm){ for(var p in itm){ if(itm.hasOwnProperty(p)){ if(!output[p]) output[p]= []; if(output[p].indexOf(itm[p])== -1) output[p].push(itm[p]); } } }); Run.expose(output)// nonstandard object to string method // returned value: (String) { animal:[ 'cat', 'dog' ], name:[ 'Rocky', 'Spot' ], value:[ 1, 2, 3 ] }
Try Underscore, it's magnificent with this kind of tasks)