Create arrays from JavaScript objects - javascript

I have some data which looks like this:
{
"obj":
[
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
What I need to do is to create 2 arrays from it.
For example:
namelist[];
agelist[];
so the result would be:
namelist: ['name1', 'name2'];
agelist: [24, 17];
My question is, how can I do this?

var namelist = [];
var agelist = [];
for(var i in obj.obj){
namelist.push(obj.obj[i].name);
agelist.push(obj.obj[i].age);
}
console.log(namelist, agelist);

Is this what U wanted ?
var zz={
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
namelist=[];
agelist=[];
zz.obj.forEach(function(rec){
namelist.push(rec.name);
agelist.push(rec.age);
})
console.log(namelist,agelist)

You could use this ES6 code, and use the unitary plus for getting the ages as numbers. Assuming your object is stored in variable data:
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
};
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
console.log(namelist);
console.log(agelist);

var arr = $.map(myObj, function(value, index) {
return [value];
});
console.log(arr);
if you are not using Jquery then:
var arr = Object.keys(myObj).map(function (key)
{ return obj[key];
});`

Make use of jquery map function or otherwise you can loop over the object and push it into array using javascript for loop and use the push() function. Refer Loop through an array in JavaScript
Jquery
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var name = $.map(data.obj, function(value, index) {
return value.name;
});
var age = $.map(data.obj, function(value, index) {
return value.age;
});
console.log(name);
console.log(age);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Javascript
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var names = [], ages=[];
data.obj.forEach(function(value, index) {
names.push(value.name);
ages.push(value.age);
});
console.log(names,ages);

Related

How to merge objects with the same properties into an Array?

I would like to merge 2 objects with the same properties into an Array.
Take this for an example:
object1 = {"id":1,
"name":name1,
"children":[{"id":2,"name":name2}]
};
object2 = {"id":3,
"name":name3,
"children":[{"id":4,"name":name4}]
};
object3 = {"id":1,
"name":name1,
"children":[{"id":6,"name":name6}]
};
var result = Object.assign(result,object1,object2,object3);
Expected result:
JSON.stringify([result]) =[
{"id":1,
"name":name1,
"children":[{"id":2,"name":name2},
{"id":6,"name":name6}]
},
{"id":3,
"name":name3,
"children":[{"id":4,"name":name4}]
}
]
Actual result:
JSON.stringify([result]) = [
{"id":3,
"name":name3,
"children":[{"id":4,"name":name4}]
}
]
Seems like Object.assign() isn't the way to go... as it will overwrite, I do not want it to overwrite, I want them to merge instead. Is there a right way to do this?
As so often, Array.prototype.reduce provides a good base for an approach like e.g. this one ...
var obj1 = {
"id": 1,
"name": "name1",
"children": [{ "id": 2, "name": "name2" }]
};
var obj2 = {
"id": 3,
"name": "name3",
"children": [{ "id": 4, "name": "name4" }]
};
var obj3 = {
"id": 1,
"name": "name1",
"children": [{ "id": 6, "name": "name6" }]
};
// Expected result: [{
// "id": 1,
// "name": name1,
// "children": [
// { "id": 2, "name": "name2" },
// { "id": 6, "name": "name6" }
// ]
// }, {
// "id": 3,
// "name": "name3",
// "children": [{"id": 4, "name": "name4" }]
// }]
function mergeEquallyLabeledTypes(collector, type) {
var key = (type.name + '#' + type.id); // identity key.
var store = collector.store;
var storedType = store[key];
if (storedType) { // merge `children` of identically named types.
storedType.children = storedType.children.concat(type.children);
} else {
store[key] = type;
collector.list.push(type);
}
return collector;
}
var result = [obj1, obj2, obj3].reduce(mergeEquallyLabeledTypes, {
store: {},
list: []
}).list;
console.log('result : ', result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Edit Note
After having been informed about changed requirements, that need to deal with a nested pattern, I will change my first provided approach into a generic solution. It will be not that difficult since there is a generically repeated pattern within the data structure. Thus I just need to make the already existing reducer function self recursive. A recursion step will be triggered after having finished a complete reducing cycle on any provided list ...
var obj1 = {
"id": 1,
"name": "name1",
"children": [{ "id": 2, "name": "name2", "children": [{ "id": 8, "name": "name8" }] }]
};
var obj2 = {
"id": 3,
"name": "name3",
"children": [{ "id": 4, "name": "name4", "children": [{ "id": 9, "name": "name9" }] }]
};
var obj3 = {
"id": 1,
"name": "name1",
"children": [{ "id": 6, "name": "name6", "children": [{ "id": 10, "name": "name10" }] }]
};
var obj4 = {
"id": 3,
"name": "name3",
"children": [{ "id": 4, "name": "name4", "children": [{ "id": 11, "name": "name11" }] }]
};
function mergeEquallyLabeledTypesRecursively(collector, type, idx, list) {
var key = (type.name + '#' + type.id); // identity key.
var store = collector.store;
var storedType = store[key];
if (storedType) { // merge `children` of identically named types.
storedType.children = storedType.children.concat(type.children);
} else {
store[key] = type;
collector.list.push(type);
}
// take repetitive data patterns into account ...
if (idx >= (list.length - 1)) {
collector.list.forEach(function (type) {
// ... behave recursive, when appropriate.
if (type.children) {
type.children = type.children.reduce(mergeEquallyLabeledTypesRecursively, {
store: {},
list: []
}).list;
}
});
}
return collector;
}
var result = [obj1, obj2, obj3, obj4].reduce(mergeEquallyLabeledTypesRecursively, {
store: {},
list: []
}).list;
console.log('result : ', result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
This might be what your after, please note it's not recursive now recursive. But your example data doesn't appear to be anyway.
const object1 = {"id":1,
"name":"name1",
"children":[{"id":2,"name":"name2"}]
};
const object2 = {"id":3,
"name":"name3",
"children":[{"id":4,"name":"name4"}]
};
const object3 = {"id":1,
"name":"name1",
"children":[
{"id":6,"name":"name6"},
{"id":7,"name":"name7"},
{"id":6,"name":"name6"}
]
};
function merge(arr) {
const idLinks = {};
const ret = [];
arr.forEach((r) => {
if (!idLinks[r.id]) idLinks[r.id] = [];
idLinks[r.id].push(r);
});
Object.keys(idLinks).forEach((k) => {
const nn = idLinks[k];
const n = nn[0];
for (let l = 1; l < nn.length; l ++) {
if (nn[l].children) {
if (!n.children) n.children = [];
n.children = n.children.concat(nn[l].children);
}
}
if (n.children && n.children.length) n.children = merge(n.children);
ret.push(n);
});
return ret;
}
var result = merge([object1,object2,object3]);
console.log(result);
/* There are two cases :
a) No duplicate children
b) Duplicate children either in (same object || different object|| both)
*/
/* =============== */
/* Case a) */
const util = require('util');
var object1 = {
"id": 1,
"name": "name1",
"children": [{ "id": 2, "name": "name2" }]
};
var object2 = {
"id": 3,
"name": "name3",
"children": [{ "id": 4, "name": "name4" }]
};
var object3 = {
"id": 1,
"name":"name1",
"children":[{"id":6,"name":"name6"}]
};
var arr = [object1,object2,object3];
var uniqueIds = [];
var filteredArray = [];
var uniqueId='';
arr.map((item,i,array)=>{
uniqueId =uniqueIds.indexOf(item.id);
uniqueId = uniqueId+1;
uniqueIds = [...uniqueIds,item.id];
if(!uniqueId){
filteredArray[i] = item;
}
if(uniqueId){
filteredArray[uniqueId-1]['children'] = [...(array[uniqueId-1].children),...(item.children)];
}
});
console.log(util.inspect(filteredArray,false,null));
/* ============================================
Case b)
Dealing with the worst case of having duplicate children in both same
and different objects
*/
object1 = {"id":1,
"name":'name1',
"children":[{"id":2,"name":'name2'},
{"id":2,"name":'name2'}]
};
object2 = {"id":3,
"name":'name3',
"children":[{"id":4,"name":'name4'}]
};
object3 = {"id":1,
"name":'name1',
"children":[{"id":6,"name":'name6'},
{"id":7,"name":'name7'},
{"id":2,"name":'name2'}]
};
arr = [object1,object2,object3];
uniqueIds = [];
uniqueId = '';
arr.map((item,i,array)=>{
uniqueId =uniqueIds.indexOf(item.id);
uniqueId = uniqueId+1;
uniqueIds = [...uniqueIds,item.id];
if(!uniqueId){
filteredArray[i] = item;
}
if(uniqueId){
filteredArray[uniqueId-1]['children'] = [...(array[uniqueId-1].children),...(item.children)];
}
/*Removing duplicate children entries*/
filteredArray[uniqueIds.indexOf(item.id)]['children'] = filteredArray[uniqueIds.indexOf(item.id)]['children']
.filter((elem, index, self) => self.findIndex((t) => {return t.id === elem.id}) === index)
})
console.log(util.inspect(filteredArray,false,null));
In functional programming way with es6 standards. I am assuming children array also contains duplicates. I enclosed the code in closures.
See the following link why I used util to print all the object in node console.log()
How can I get the full object in Node.js's console.log(), rather than '[Object]'?
(function() {
'use strict';
const util = require('util');
/** string constants */
const ID = 'id';
const CHILDREN = 'children';
/* Objects to modify */
const object1 = {
"id": 1,
"name": "name1",
"children": [
{ "id": 2, "name": "name2" },
{ "id": 5, "name": "name5" },
{ "id": 7, "name": "name7" }
]
};
const object2 = {
"id": 3,
"name": "name3",
"children": [
{ "id": 4, "name": "name4" }
]
};
const object3 = {
"id": 1,
"name": "name1",
"children": [
{ "id": 5, "name": "name5" },
{ "id": 6, "name": "name6" }
]
};
/**
* Concates the arrays
* #param { array } - a
* #param { array } - b
*/
const merge = (a, b) => {
return a.concat(b);
};
/**
* Removes Duplicates from the given array based on ID
* #param { array } - array to remove duplicates
* #return { array } - array without duplicates
*/
const removeDuplicates = (arr) => {
return arr.filter((obj, pos, arr) => {
return arr.map((m) => {
return m[ID];
}).indexOf(obj[ID]) === pos;
});
}
/**
* Groups items in array with particular key
* Currying technique
* #param { prop } - key to group
* #return { () => {} } - Method which in turn takes array as argument
*/
const groupBy = (prop) => (array) => {
return array.reduce((groups, item) => {
const val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
/**
* Object containing grouped-items by particuar key
*/
const grouped = groupBy(ID)([object1, object2, object3]);
/**
* Removing the duplicates of children
* Remember map also mutates the array of objects key's value
* but not data type
*/
Object.keys(grouped).map((key, position) => {
grouped[key].reduce((a, b) => {
a[CHILDREN] = removeDuplicates(a[CHILDREN].concat(b[CHILDREN]));
});
});
/**
* Desired final output
*/
const final = Object.keys(grouped)
.map((key) => removeDuplicates(grouped[key]))
.reduce(merge, []);
console.log(util.inspect(final, false, null))})();
const object1 = {
"id":1,
"name":"name1",
"children":[{"id":2,"name":"name2"}]
};
const object2 = {
"id":3,
"name":"name3",
"children":[{"id":4,"name":"name4"}]
};
const object3 = {
"id":1,
"name":"name1",
"children":[{"id":6,"name":"name6"}]
};
var array = [object1,object2,object3];
var array2 = [object1,object2,object3];
function uniquearray(obj){
var result =[];
for(var i=0;i<array.length;i++){
if(obj.id == array[i].id){
result.push(array[i])
array.splice(i,1)
}
}
return result;
}
var arrayofuniarrays = []
for(var i=0;i<array2.length;i++){
arrayofuniarrays.push(uniquearray(array2[i]))
}
for(var i=0;i<arrayofuniarrays.length;i++){
for(var j=1;j<arrayofuniarrays[i].length; j++){
arrayofuniarrays[i][0].children.push(arrayofuniarrays[i][j].children)
arrayofuniarrays[i].splice(j,1)
}
}
var resul = arrayofuniarrays.reduce(function(a, b){return a.concat(b)},[])
console.log(resul)
Here is a sketch example of how to do this. It leverages a mapped type using your id as a key to ensure each item only appears once. It adds all of the children to an array based on the id.
If you needed to enforce the same behaviour on the children, you could use the same technique.
I have split this into multiple iterations to show you the individual parts in play.
Usually, it is more efficient to avoid creating objects that need to be zipped back up if you can.
const object1 = {
"id": 1,
"name": "name1",
"children": [{ "id": 2, "name": "name2" }]
};
const object2 = {
"id": 3,
"name": "name3",
"children": [{ "id": 4, "name": "name4" }]
};
const object3 = {
"id": 1,
"name":"name1",
"children":[{"id":6,"name":"name6"}]
};
const all = [object1, object2, object3];
// Use a map like a dictionary to enforce unique keys
const mapped = {};
for (let obj of all) {
if (!mapped[obj.id]) {
mapped[obj.id] = obj;
continue;
}
mapped[obj.id].children.push(obj.children);
}
console.log('Mapped ==> '+JSON.stringify(mapped));
// If you want to convert the mapped type to an array
const result = [];
for (let key in mapped) {
result.push(mapped[key]);
}
console.log('Array ==> '+JSON.stringify(result));
Building on #Peter Seliger's answer here, I derived with the following method to merge arrays with deeply nested children.
Given the following objects:
var obj1 = {
"id": 1,
"name": "name1",
"children": [{ "id": 2, "name": "name2", children:[{ "id":8, "name": "name8" }] }]
};
var obj2 = {
"id": 3,
"name": "name3",
"children": [{ "id": 4, "name": "name4", children:[{ "id":9, "name": "name9" }] }]
};
var obj3 = {
"id": 1,
"name": "name1",
"children": [{ "id": 6, "name": "name6", children:[{ "id":10, "name": "name10" }] }]
};
var obj4 = {
"id": 3,
"name": "name3",
"children": [{ "id": 4, "name": "name4", children:[{ "id":11, "name": "name11" }] }]
};
First we merge the parents
function mergeEquallyLabeledTypes(collector, type) {
var key = (type.name + '#' + type.id); // identity key.
var store = collector.store;
var storedType = store[key];
if (storedType) { // merge `children` of identically named types.
if(storedType.children)
storedType.children = storedType.children.concat(type.children);
} else {
store[key] = type;
collector.list.push(type);
}
return collector;
}
var result = [obj1, obj2, obj3, obj4].reduce(mergeEquallyLabeledTypes, {
store: {},
list: []
}).list;
Then we merge the children and subchildren if any.
for(let i=0; i<result.length; i++){
var children = result[i].children;
if(children){
var reducedChildren = children.reduce(mergeEquallyLabeledTypes, {store: {}, list: []}).list;
for(let j=0; j<reducedChildren.length; j++){
var subchildren = reducedChildren[j].children;
if(subchildren){
var reducedSubchildren = subchildren.reduce(mergeEquallyLabeledTypes, {store: {}, list: []}).list;
reducedChildren[j].children = reducedSubchildren;
}
}
result[i].children = reducedChildren;
}
}
Finally the result will be what I'll parse into my website.
console.log('result : ', result);
I am able to get the expected result.
// result: [{
// "id": 1,
// "name": name1,
// "children": [
// { "id": 2, "name": "name2", children:[{ "id":8, "name": "name8" }] },
// { "id": 6, "name": "name6", children:[{ "id":10, "name": "name10" }] }
// ]
// }, {
// "id": 3,
// "name": "name3",
// "children": [{"id": 4, "name": "name4", children:[
// { "id":9, "name": "name9" },
// { "id":11, "name": "name11" }
// ]
// }
// ]
// }]
However, this might not be too efficient as I'll need to keep adding on to the merging of children/subchildren method if my tree get nested with more levels. (e.g. subsubchildren, subsubsubchildren and so on...)
Is there any more efficient way to do this?
const object1 = {
id:1,
name:'a',
}
const object2 = {
id:3,
name:'b',
}
const object3 = {
id:1,
name:'c',
}
const originArr = [object1, object2, object3]
const idArr = [object1.id, object2.id, object3.id]
const newIdArr = []
for (let id of idArr) {
if (newIdArr.indexOf(id)) newIdArr.push(id)
}
const result = newIdArr.map(id => {
let names = []
for (obj of originArr) {
if (id === obj.id) names.push(obj.name)
}
return { id, names }
})
console.log(result)

Common objects in two objects

This function returns diff between two objects , i need to modify it to return common objects. Any help is appreciated.
Array sample:
var array1 = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
}, {
"Name": "Triple",
"URL": "zzz",
"ID": 567
}];
var arrar2 = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
}, {
"Name": "index",
"URL": "zzz",
"ID": 567
}];
// expected result
var resultArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
},
}];
Current code:
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if (origObj.name == destObj.name) return true
})
if (!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if (origObj.name == destObj.name) return true
})
if (!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
If all you want is to look for things that are the same in both arrays, you only need to loop over one of them. Something along these lines should work:
function objSame(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.name == destObj.name) return true
})
if(check) {
destObj.desc = 'Same in both'
resultArray.push(destObj)
}
})
return resultArray
}
To find array elements that have a common Name property value, you could use a Map to avoid O(n²) time complexity. That map would have the objects from the first array keyed by their name. Pass it as the this object to a filter on the second array:
function objCommon(array1, array2) {
return array2.filter(function (obj) {
return this.has(obj.Name);
}, new Map(array1.map(obj => [obj.Name, obj])));
}
var array1= [
{ "Name": "Single", "URL": "xxx", "ID": 123 },
{ "Name": "Double", "URL": "yyy", "ID": 888},
{ "Name": "Triple", "URL": "zzz", "ID": 567 }];
var array2= [
{ "Name": "Single", "URL": "xxx", "ID": 123 },
{ "Name": "Double", "URL": "yyy", "ID": 888 },
{ "Name": "index", "URL": "zzz", "ID": 567 }];
var result = objCommon(array1, array2);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
That's not your code, but the following function will return all matches by exploring both arrays with two forEach() loops. Algorithm complexity is given by array1.length * array2.length. Don't use for large arrays! But it's the easiest way to think of it. Indeed the first think that comes to my mind is checking every element of array2 for every element of array1 and compare them.
var array1 = ['DETE', 'Ivany', 'James', 'Don', 'Crakcer']
var array2 = ['Jamies', 'Ivanyy', 'DETE', 'Don']
function objMatch(array1,array2) {
var matches = [];
array1.forEach(function(element1) {
array2.forEach(function(element2) {
if(element1 == element2) {
matches.push(element1);
}
});
});
return matches;
}
console.log(objMatch(array1, array2));
// will return ['DETE', 'Don']
Another way to do with only one loop is to use sort(), credit to jeremy
var array1 = ["cat", "sum","fun", "run", "gut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
var arrayMatch = function(array1, array2) {
var matches = [];
array1.sort();
array2.sort();
for (var i = 0; i < array1.length; i += 1) {
if (array2.indexOf(array1[i]) > -1) {
matches.push(array1[i]);
}
}
return matches;
}
console.log(arrayMatch(array1,array2))
And yet another way to do it is by using Array.prototype.filter, credit to Paul S.
var array1 = ['DETE', 'Ivany', 'James', 'Don', 'Crakcer']
var array2 = ['Jamies', 'Ivanyy', 'DETE', 'Don']
function arrayMatch(array1, array2) {
var t;
if (array1.length > array2.length) t = array2, array2 = array1, array1 = t;
return array1.filter(function (e) {
return array2.indexOf(e) > -1;
});
}
console.log(arrayMatch(array1, array2));

Creating a new object from array of objects and grouping by specific matching key/value

Example of the object data I am dealing with
var myData = [{
"name": "John",
"age": 30,
"interest": "Baseball"
},
{
"name": "Bob",
"age": 21,
"interest": "Baseball"
},
{
"name" : "Sally",
"age" : 29,
"interest": "Tennis"
}]
I am trying to figure out the easiest way to group them by interests. I am open to using lodash or underscore, but I cannot get the final result to look like this....
I want this to be the output:
[{ "Baseball" : [{
"name": "John",
"age" : 30
},
{
"name" : "Bob",
"age" : 21
}]
},
{ "Tennis" : [{
"name" : "Sally",
"age" : 21
}]
}];
Basically, each interest becomes a new object key containing all of the matched values within arrays.
I am having trouble constructing this output. Any assistance would be greatly appreciated. I prefer to use lodash/underscore to keep things very easy.
Thank you!
You could use Array.reduce for this:
var myData = [
{
"name": "John",
"age": 30,
"interest": "Baseball"
},
{
"name": "Bob",
"age": 21,
"interest": "Baseball"
},
{
"name" : "Sally",
"age" : 29,
"interest": "Tennis"
}];
var result = myData.reduce(function(entities, obj) {
entities[obj.interest] = (entities[obj.interest] || []).concat({
name: obj.name,
age: obj.age
});
return entities;
}, {});
console.log(result);
A little bit more general approach:
function groupBy(data, key, tFunc) {
mapFunc = (typeof tFunc === "function")? tFunc: function(o) { return o };
return (Array.isArray(data)?data:[]).reduce(function(entities, o) {
if(o[key]) {
entities[o[key]] = (entities[o[key]] || []).concat(tFunc(o));
}
return entities;
}, {});
}
// test code
var myData = [
{
"name": "John",
"age": 30,
"interest": "Baseball"
},
{
"name": "Bob",
"age": 21,
"interest": "Baseball"
},
{
"name" : "Sally",
"age" : 29,
"interest": "Tennis"
}];
var result = groupBy(myData, "interest", function(o) { return { name: o.name, age: o.age}});
console.log(result);
var result2 = groupBy(myData, "age", function(o) { return o.name});
console.log(result2);
A group-by operation can be done by matching values in a dictionary (hashtable). In JavaScript all objects are dictionaries with property-names as the keys, for values we use arrays.
For example (press the "Run code snippet" button below to see the results):
function groupBy( input, propertyName ) {
var output = {};
for(var i = 0; i < input.length; i++) {
var groupByValue = input[i][propertyName];
if( !(groupByValue in output) ) {
output[ groupByValue ] = [];
}
var dolly = cloneObjectButIgnoreProperty( input[i], propertyName );
output[ groupByValue ].push( dolly );
}
return output;
}
function cloneObjectButIgnoreProperty( value, ignorePropertyName ) {
var dolly = {};
var propertyNames = Object.keys( value );
for( var i = 0; i < propertyNames .length; i++ ) {
var propertyName = propertyNames[i];
if( propertyName == ignorePropertyName ) continue;
dolly[propertyName ] = value[propertyName ];
}
return dolly;
}
var myData = [
{
"name": "John",
"age": 30,
"interest": "Baseball"
},
{
"name": "Bob",
"age": 21,
"interest": "Baseball"
},
{
"name" : "Sally",
"age" : 29,
"interest": "Tennis"
}
];
var groupedByInterest = groupBy( myData, 'interest' );
console.log( "By interest:" );
console.log( groupedByInterest );
var groupedByName = groupBy( myData, 'name' );
console.log( "By name:" );
console.log( groupedByName );
var groupedByAge = groupBy( myData, 'age' );
console.log( "By age:" );
console.log( groupedByAge );
The solution using Array.prototype.reduce() function:
var myData = [{ "name": "John", "age": 30, "interest": "Baseball" }, { "name": "Bob", "age": 21, "interest": "Baseball" }, { "name" : "Sally", "age" : 29, "interest": "Tennis" }],
result = myData.reduce(function (r, o) {
r[o.interest] = r[o.interest] || [];
r[o.interest].push({name: o.name, age: o.age});
return r;
}, {});
console.log(result);
var myData = [{name:"John",age:30,interest:"Baseball"},{name:"Bob",age:21,interest:"Baseball"},{name:"Sally",age:29,interest:"Tennis"}],
result = [],
interests = [...new Set(myData.map(v => v.interest))];
interests.forEach(v => result.push({ [v] : [] }));
myData.forEach((v,i) => result.forEach((c,i) => Object.keys(c)[0] == v.interest ? result[i][v.interest].push({name: v.name, age: v.age}) : c))
console.log(result);

how to count similar value object in json?

I have this JSON structure:
[{
"name": "ankit",
"DOB": "23/06"
}, {
"name": "kapil",
"DOB": "26/06"
}, {
"name": "ankit",
"DOB": "27/06"
}]
I want to count similar object with value ankit. How can I do this?
You can use Array.prototype.filter():
var count = json.filter(function (el) {
return el.name == 'ankit';
}).length;
How about:
let a = [
{ "name": "ankit", "DOB": "23/06" },
{ "name": "kapil", "DOB": "26/06" },
{ "name": "ankit", "DOB": "27/06" }
];
let count = 0;
a.forEach(item => {
if (item.name === "ankit") {
count++;
}
});
(code in playground)
You could use an object for counting and get the wanted count for a name with the name as property.
var data = [{ "name": "ankit", "DOB": "23/06" }, { "name": "kapil", "DOB": "26/06" }, { "name": "ankit", "DOB": "27/06" }],
count = {};
data.forEach(function (a) {
count[a.name] = (count[a.name] || 0) + 1;
});
console.log(count);
console.log(count['ankit']);
You can use the reduce method to reduce the items that have the name ankit to a number.
var items = [
{
name: 'ankit',
DOB: '23/06'
},
{
name: 'kapil',
DOB: '26/06'
},
{
name: 'ankit',
DOB: '27/06'
}
]
var numItems = items.reduce(function (count, item) {
return item.name === 'ankit' ? count + 1 : count
}, 0)
document.write('Number of items with the name `ankit`: ' + numItems)
1. Get the object from JSON:
var obj = JSON.parse(text);
2. Get your array filtered:
var count = obj.filter(function(obj) { return obj.name == "ankit" }).length;

How to transform JavaScript hashmap?

i'm trying to create a <String, Array()> map from a json object.
Imagine i got this json structure:
[
{
"userId": "123123",
"password": "fafafa",
"age": "21"
},
{
"userId": "321321",
"password": "nana123",
"age": "34"
}
]
The map i want to create would be:
key (string), value (array)
{
"userId": [
"123123",
"321321"
],
"password": [
"fafafa",
"nana123"
],
"age": [
"21",
"34"
]
}
Is it possible to do this? :/
Thanks in advance.
Demo
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
var list = JSON.parse(json);
var output = {};
for(var i=0; i<list.length; i++)
{
for(var key in list[i])
{
if(list[i].hasOwnProperty(key))
{
if(typeof output[key] == 'undefined')
{
output[key] = [];
}
output[key].push(list[i][key]);
}
}
}
document.write(JSON.stringify(output));
Outputs:
{"userId":["123123","321321"],"password":["fafafa","nana123"],"age":["21","34"]}
function mergeAttributes(arr) {
return arr.reduce(function(memo, obj) { // For each object in the input array.
Object.keys(obj).forEach(function(key) { // For each key in the object.
if (!(key in memo)) { memo[key] = []; } // Create an array the first time.
memo[key].push(obj[key]); // Add this property to the reduced object.
});
return memo;
}, {});
}
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
mergeAttributes(JSON.parse(json));
// {
// "userId": ["123123", "321321"],
// "password": ["fafafa", "nana123"],
// "age": ["21", "34"]
// }
Javascript's JSON.stringify will help you to convert any JSON compliant object model into a JSON string.

Categories

Resources