Does Javascript have something similar to python's dict comprehension? [duplicate]
up vote
0
down vote
favorite
This question already has an answer here:
How to group an array of objects by key
9 answers
I have a set of data I'm collecting that outputs something like this:
[
{
hostName: 'server1',
service: 'service1',
perfData: 'unique string5',
state: 1
},
{
hostName: 'server1',
service: 'service2',
perfData: 'unique string4',
state: 1
},
{
hostName: 'server1',
service: 'service3',
perfData: 'unique string3',
state: 1
},
{
hostName: 'server2',
service: 'service1',
perfData: 'unique string2',
state: 1
},
{
hostName: 'server2',
service: 'service2',
perfData: 'unique string1',
state: 1
}
]
I'm trying to loop through this array of objects with javascript to output the following:
let desiredOutput = [{'server1': [{
service: 'service1',
perfData: 'unique string1',
state: 1
},
{
service: 'service2',
perfData: 'unique string1',
state: 1
},
{
service: 'service3',
perfData: 'unique string1',
state: 1
}],
'server2': {
service: 'service1',
perfData: 'unique string1',
state: 1
}
}];
Does Javascript have something similar to dict comprehension? Not sure how to loop through an array of objects and merge them and make them an object with an array of objects. In python I could use something like this:
raw_data = [{'hostName': 'server1', 'serviceName': 'service1'}, {'hostName': 'server1', 'serviceName': 'service2'}, {'hostName': 'server1', 'serviceName': 'service3'}, {'hostName': 'server2', 'serviceName': 'service1'}, {'hostName': 'server2', 'serviceName': 'service2'}]
services = defaultdict(list)
for service in raw_data:
host_name = service.get('hostName')
service_name = service.get('service')
new_dict = {'hostName': host_name, 'serviceName': service_name}
services[new_dict['hostName']].append(new_dict)
print(services)
I found something close with this Merge javascript objects in array with same key but not quite what I'm looking for.
javascript arrays sorting object dictionary-comprehension
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
marked as duplicate by trincot
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |
up vote
0
down vote
favorite
This question already has an answer here:
How to group an array of objects by key
9 answers
I have a set of data I'm collecting that outputs something like this:
[
{
hostName: 'server1',
service: 'service1',
perfData: 'unique string5',
state: 1
},
{
hostName: 'server1',
service: 'service2',
perfData: 'unique string4',
state: 1
},
{
hostName: 'server1',
service: 'service3',
perfData: 'unique string3',
state: 1
},
{
hostName: 'server2',
service: 'service1',
perfData: 'unique string2',
state: 1
},
{
hostName: 'server2',
service: 'service2',
perfData: 'unique string1',
state: 1
}
]
I'm trying to loop through this array of objects with javascript to output the following:
let desiredOutput = [{'server1': [{
service: 'service1',
perfData: 'unique string1',
state: 1
},
{
service: 'service2',
perfData: 'unique string1',
state: 1
},
{
service: 'service3',
perfData: 'unique string1',
state: 1
}],
'server2': {
service: 'service1',
perfData: 'unique string1',
state: 1
}
}];
Does Javascript have something similar to dict comprehension? Not sure how to loop through an array of objects and merge them and make them an object with an array of objects. In python I could use something like this:
raw_data = [{'hostName': 'server1', 'serviceName': 'service1'}, {'hostName': 'server1', 'serviceName': 'service2'}, {'hostName': 'server1', 'serviceName': 'service3'}, {'hostName': 'server2', 'serviceName': 'service1'}, {'hostName': 'server2', 'serviceName': 'service2'}]
services = defaultdict(list)
for service in raw_data:
host_name = service.get('hostName')
service_name = service.get('service')
new_dict = {'hostName': host_name, 'serviceName': service_name}
services[new_dict['hostName']].append(new_dict)
print(services)
I found something close with this Merge javascript objects in array with same key but not quite what I'm looking for.
javascript arrays sorting object dictionary-comprehension
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
marked as duplicate by trincot
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
JavaScript has several built inArray.prototypemethods for traverse and transforming arrays. More information can be found at the MDN for Arrays developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Robert Mennell
yesterday
Also in JavaScript we just access them using the bracket notation:object[key]orobject.keyif the key is known. As for making a new object, object literals are allowed to use computed values{ [key] : value }and more information can be found here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Robert Mennell
yesterday
The Python code you posted does not have a "dict comprehension". You are iterating in a conventionalforloop and then building yourservicesdictionary. With Javascript, the most appropriate array method for this case seems likereduce.
– slider
yesterday
I don't see how this relates to dict comprehension as your Python snippet does not use it. Python dict comprehension looks like{ key: value for key, value in iterable }
– trincot
yesterday
Shouldn't your result include{"service": "service2", "perfData": "unique string1", "state": 1}in theserver2key?
– ggorlen
yesterday
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
This question already has an answer here:
How to group an array of objects by key
9 answers
I have a set of data I'm collecting that outputs something like this:
[
{
hostName: 'server1',
service: 'service1',
perfData: 'unique string5',
state: 1
},
{
hostName: 'server1',
service: 'service2',
perfData: 'unique string4',
state: 1
},
{
hostName: 'server1',
service: 'service3',
perfData: 'unique string3',
state: 1
},
{
hostName: 'server2',
service: 'service1',
perfData: 'unique string2',
state: 1
},
{
hostName: 'server2',
service: 'service2',
perfData: 'unique string1',
state: 1
}
]
I'm trying to loop through this array of objects with javascript to output the following:
let desiredOutput = [{'server1': [{
service: 'service1',
perfData: 'unique string1',
state: 1
},
{
service: 'service2',
perfData: 'unique string1',
state: 1
},
{
service: 'service3',
perfData: 'unique string1',
state: 1
}],
'server2': {
service: 'service1',
perfData: 'unique string1',
state: 1
}
}];
Does Javascript have something similar to dict comprehension? Not sure how to loop through an array of objects and merge them and make them an object with an array of objects. In python I could use something like this:
raw_data = [{'hostName': 'server1', 'serviceName': 'service1'}, {'hostName': 'server1', 'serviceName': 'service2'}, {'hostName': 'server1', 'serviceName': 'service3'}, {'hostName': 'server2', 'serviceName': 'service1'}, {'hostName': 'server2', 'serviceName': 'service2'}]
services = defaultdict(list)
for service in raw_data:
host_name = service.get('hostName')
service_name = service.get('service')
new_dict = {'hostName': host_name, 'serviceName': service_name}
services[new_dict['hostName']].append(new_dict)
print(services)
I found something close with this Merge javascript objects in array with same key but not quite what I'm looking for.
javascript arrays sorting object dictionary-comprehension
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
This question already has an answer here:
How to group an array of objects by key
9 answers
I have a set of data I'm collecting that outputs something like this:
[
{
hostName: 'server1',
service: 'service1',
perfData: 'unique string5',
state: 1
},
{
hostName: 'server1',
service: 'service2',
perfData: 'unique string4',
state: 1
},
{
hostName: 'server1',
service: 'service3',
perfData: 'unique string3',
state: 1
},
{
hostName: 'server2',
service: 'service1',
perfData: 'unique string2',
state: 1
},
{
hostName: 'server2',
service: 'service2',
perfData: 'unique string1',
state: 1
}
]
I'm trying to loop through this array of objects with javascript to output the following:
let desiredOutput = [{'server1': [{
service: 'service1',
perfData: 'unique string1',
state: 1
},
{
service: 'service2',
perfData: 'unique string1',
state: 1
},
{
service: 'service3',
perfData: 'unique string1',
state: 1
}],
'server2': {
service: 'service1',
perfData: 'unique string1',
state: 1
}
}];
Does Javascript have something similar to dict comprehension? Not sure how to loop through an array of objects and merge them and make them an object with an array of objects. In python I could use something like this:
raw_data = [{'hostName': 'server1', 'serviceName': 'service1'}, {'hostName': 'server1', 'serviceName': 'service2'}, {'hostName': 'server1', 'serviceName': 'service3'}, {'hostName': 'server2', 'serviceName': 'service1'}, {'hostName': 'server2', 'serviceName': 'service2'}]
services = defaultdict(list)
for service in raw_data:
host_name = service.get('hostName')
service_name = service.get('service')
new_dict = {'hostName': host_name, 'serviceName': service_name}
services[new_dict['hostName']].append(new_dict)
print(services)
I found something close with this Merge javascript objects in array with same key but not quite what I'm looking for.
This question already has an answer here:
How to group an array of objects by key
9 answers
javascript arrays sorting object dictionary-comprehension
javascript arrays sorting object dictionary-comprehension
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked yesterday
Ian Clark
11
11
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Ian Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
marked as duplicate by trincot
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by trincot
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
JavaScript has several built inArray.prototypemethods for traverse and transforming arrays. More information can be found at the MDN for Arrays developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Robert Mennell
yesterday
Also in JavaScript we just access them using the bracket notation:object[key]orobject.keyif the key is known. As for making a new object, object literals are allowed to use computed values{ [key] : value }and more information can be found here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Robert Mennell
yesterday
The Python code you posted does not have a "dict comprehension". You are iterating in a conventionalforloop and then building yourservicesdictionary. With Javascript, the most appropriate array method for this case seems likereduce.
– slider
yesterday
I don't see how this relates to dict comprehension as your Python snippet does not use it. Python dict comprehension looks like{ key: value for key, value in iterable }
– trincot
yesterday
Shouldn't your result include{"service": "service2", "perfData": "unique string1", "state": 1}in theserver2key?
– ggorlen
yesterday
add a comment |
JavaScript has several built inArray.prototypemethods for traverse and transforming arrays. More information can be found at the MDN for Arrays developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Robert Mennell
yesterday
Also in JavaScript we just access them using the bracket notation:object[key]orobject.keyif the key is known. As for making a new object, object literals are allowed to use computed values{ [key] : value }and more information can be found here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Robert Mennell
yesterday
The Python code you posted does not have a "dict comprehension". You are iterating in a conventionalforloop and then building yourservicesdictionary. With Javascript, the most appropriate array method for this case seems likereduce.
– slider
yesterday
I don't see how this relates to dict comprehension as your Python snippet does not use it. Python dict comprehension looks like{ key: value for key, value in iterable }
– trincot
yesterday
Shouldn't your result include{"service": "service2", "perfData": "unique string1", "state": 1}in theserver2key?
– ggorlen
yesterday
JavaScript has several built in
Array.prototype methods for traverse and transforming arrays. More information can be found at the MDN for Arrays developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…– Robert Mennell
yesterday
JavaScript has several built in
Array.prototype methods for traverse and transforming arrays. More information can be found at the MDN for Arrays developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…– Robert Mennell
yesterday
Also in JavaScript we just access them using the bracket notation:
object[key] or object.key if the key is known. As for making a new object, object literals are allowed to use computed values { [key] : value } and more information can be found here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…– Robert Mennell
yesterday
Also in JavaScript we just access them using the bracket notation:
object[key] or object.key if the key is known. As for making a new object, object literals are allowed to use computed values { [key] : value } and more information can be found here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…– Robert Mennell
yesterday
The Python code you posted does not have a "dict comprehension". You are iterating in a conventional
for loop and then building your services dictionary. With Javascript, the most appropriate array method for this case seems like reduce.– slider
yesterday
The Python code you posted does not have a "dict comprehension". You are iterating in a conventional
for loop and then building your services dictionary. With Javascript, the most appropriate array method for this case seems like reduce.– slider
yesterday
I don't see how this relates to dict comprehension as your Python snippet does not use it. Python dict comprehension looks like
{ key: value for key, value in iterable }– trincot
yesterday
I don't see how this relates to dict comprehension as your Python snippet does not use it. Python dict comprehension looks like
{ key: value for key, value in iterable }– trincot
yesterday
Shouldn't your result include
{"service": "service2", "perfData": "unique string1", "state": 1} in the server2 key?– ggorlen
yesterday
Shouldn't your result include
{"service": "service2", "perfData": "unique string1", "state": 1} in the server2 key?– ggorlen
yesterday
add a comment |
2 Answers
2
active
oldest
votes
up vote
0
down vote
Not sure about dict comprehensions (you're not using them in your snippet), but defaultdict could be done quite easily:
class DefaultMap extends Map {
constructor(fn, entries = ) {
super(entries);
this.fn = fn;
}
get(key) {
if (!this.has(key))
this.set(key, this.fn());
return super.get(key)
}
}
services = new DefaultMap(Array)
for (let service of raw_data)
services.get(service.hostName).push(service)
Unfortunately, JS doesn't come with "batteries included", so you have to code stuff like that from scratch or look around for a library.
add a comment |
up vote
0
down vote
Your output structure is a bit strange (an array of one element?). Using reduce is a reasonable approach, building arrays for each unique key:
const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);
why nota[name] = name in a ? [...a[name], e] : [e];if you want to make concatenation smaller, or usea[name] = name in a ? a[name].push(e) && a[name] : [e];so that you can avoid the complexity problem your example introduces?
– Robert Mennell
yesterday
All three options seem more or less the same complexity level to my mind, but thanks for the alternatives.
– ggorlen
yesterday
[...a[name], e]will create a new array, traverse the original, then push the new element.a[name].concat([e])will create a new array by traversing the first to copy it, and then traverse the second to push(most complex).a[name].push(e) && a[name]will push onto the array and then return it(least complex). All three have slightly different complexity
– Robert Mennell
yesterday
1
Oh, you're talking about time complexity/efficiency--I thought you were talking readability. That's fair enough.
– ggorlen
yesterday
add a comment |
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
Not sure about dict comprehensions (you're not using them in your snippet), but defaultdict could be done quite easily:
class DefaultMap extends Map {
constructor(fn, entries = ) {
super(entries);
this.fn = fn;
}
get(key) {
if (!this.has(key))
this.set(key, this.fn());
return super.get(key)
}
}
services = new DefaultMap(Array)
for (let service of raw_data)
services.get(service.hostName).push(service)
Unfortunately, JS doesn't come with "batteries included", so you have to code stuff like that from scratch or look around for a library.
add a comment |
up vote
0
down vote
Not sure about dict comprehensions (you're not using them in your snippet), but defaultdict could be done quite easily:
class DefaultMap extends Map {
constructor(fn, entries = ) {
super(entries);
this.fn = fn;
}
get(key) {
if (!this.has(key))
this.set(key, this.fn());
return super.get(key)
}
}
services = new DefaultMap(Array)
for (let service of raw_data)
services.get(service.hostName).push(service)
Unfortunately, JS doesn't come with "batteries included", so you have to code stuff like that from scratch or look around for a library.
add a comment |
up vote
0
down vote
up vote
0
down vote
Not sure about dict comprehensions (you're not using them in your snippet), but defaultdict could be done quite easily:
class DefaultMap extends Map {
constructor(fn, entries = ) {
super(entries);
this.fn = fn;
}
get(key) {
if (!this.has(key))
this.set(key, this.fn());
return super.get(key)
}
}
services = new DefaultMap(Array)
for (let service of raw_data)
services.get(service.hostName).push(service)
Unfortunately, JS doesn't come with "batteries included", so you have to code stuff like that from scratch or look around for a library.
Not sure about dict comprehensions (you're not using them in your snippet), but defaultdict could be done quite easily:
class DefaultMap extends Map {
constructor(fn, entries = ) {
super(entries);
this.fn = fn;
}
get(key) {
if (!this.has(key))
this.set(key, this.fn());
return super.get(key)
}
}
services = new DefaultMap(Array)
for (let service of raw_data)
services.get(service.hostName).push(service)
Unfortunately, JS doesn't come with "batteries included", so you have to code stuff like that from scratch or look around for a library.
answered yesterday
georg
143k33193290
143k33193290
add a comment |
add a comment |
up vote
0
down vote
Your output structure is a bit strange (an array of one element?). Using reduce is a reasonable approach, building arrays for each unique key:
const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);
why nota[name] = name in a ? [...a[name], e] : [e];if you want to make concatenation smaller, or usea[name] = name in a ? a[name].push(e) && a[name] : [e];so that you can avoid the complexity problem your example introduces?
– Robert Mennell
yesterday
All three options seem more or less the same complexity level to my mind, but thanks for the alternatives.
– ggorlen
yesterday
[...a[name], e]will create a new array, traverse the original, then push the new element.a[name].concat([e])will create a new array by traversing the first to copy it, and then traverse the second to push(most complex).a[name].push(e) && a[name]will push onto the array and then return it(least complex). All three have slightly different complexity
– Robert Mennell
yesterday
1
Oh, you're talking about time complexity/efficiency--I thought you were talking readability. That's fair enough.
– ggorlen
yesterday
add a comment |
up vote
0
down vote
Your output structure is a bit strange (an array of one element?). Using reduce is a reasonable approach, building arrays for each unique key:
const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);
why nota[name] = name in a ? [...a[name], e] : [e];if you want to make concatenation smaller, or usea[name] = name in a ? a[name].push(e) && a[name] : [e];so that you can avoid the complexity problem your example introduces?
– Robert Mennell
yesterday
All three options seem more or less the same complexity level to my mind, but thanks for the alternatives.
– ggorlen
yesterday
[...a[name], e]will create a new array, traverse the original, then push the new element.a[name].concat([e])will create a new array by traversing the first to copy it, and then traverse the second to push(most complex).a[name].push(e) && a[name]will push onto the array and then return it(least complex). All three have slightly different complexity
– Robert Mennell
yesterday
1
Oh, you're talking about time complexity/efficiency--I thought you were talking readability. That's fair enough.
– ggorlen
yesterday
add a comment |
up vote
0
down vote
up vote
0
down vote
Your output structure is a bit strange (an array of one element?). Using reduce is a reasonable approach, building arrays for each unique key:
const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);Your output structure is a bit strange (an array of one element?). Using reduce is a reasonable approach, building arrays for each unique key:
const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);edited yesterday
answered yesterday
ggorlen
5,6813825
5,6813825
why nota[name] = name in a ? [...a[name], e] : [e];if you want to make concatenation smaller, or usea[name] = name in a ? a[name].push(e) && a[name] : [e];so that you can avoid the complexity problem your example introduces?
– Robert Mennell
yesterday
All three options seem more or less the same complexity level to my mind, but thanks for the alternatives.
– ggorlen
yesterday
[...a[name], e]will create a new array, traverse the original, then push the new element.a[name].concat([e])will create a new array by traversing the first to copy it, and then traverse the second to push(most complex).a[name].push(e) && a[name]will push onto the array and then return it(least complex). All three have slightly different complexity
– Robert Mennell
yesterday
1
Oh, you're talking about time complexity/efficiency--I thought you were talking readability. That's fair enough.
– ggorlen
yesterday
add a comment |
why nota[name] = name in a ? [...a[name], e] : [e];if you want to make concatenation smaller, or usea[name] = name in a ? a[name].push(e) && a[name] : [e];so that you can avoid the complexity problem your example introduces?
– Robert Mennell
yesterday
All three options seem more or less the same complexity level to my mind, but thanks for the alternatives.
– ggorlen
yesterday
[...a[name], e]will create a new array, traverse the original, then push the new element.a[name].concat([e])will create a new array by traversing the first to copy it, and then traverse the second to push(most complex).a[name].push(e) && a[name]will push onto the array and then return it(least complex). All three have slightly different complexity
– Robert Mennell
yesterday
1
Oh, you're talking about time complexity/efficiency--I thought you were talking readability. That's fair enough.
– ggorlen
yesterday
why not
a[name] = name in a ? [...a[name], e] : [e]; if you want to make concatenation smaller, or use a[name] = name in a ? a[name].push(e) && a[name] : [e]; so that you can avoid the complexity problem your example introduces?– Robert Mennell
yesterday
why not
a[name] = name in a ? [...a[name], e] : [e]; if you want to make concatenation smaller, or use a[name] = name in a ? a[name].push(e) && a[name] : [e]; so that you can avoid the complexity problem your example introduces?– Robert Mennell
yesterday
All three options seem more or less the same complexity level to my mind, but thanks for the alternatives.
– ggorlen
yesterday
All three options seem more or less the same complexity level to my mind, but thanks for the alternatives.
– ggorlen
yesterday
[...a[name], e] will create a new array, traverse the original, then push the new element. a[name].concat([e]) will create a new array by traversing the first to copy it, and then traverse the second to push(most complex). a[name].push(e) && a[name] will push onto the array and then return it(least complex). All three have slightly different complexity– Robert Mennell
yesterday
[...a[name], e] will create a new array, traverse the original, then push the new element. a[name].concat([e]) will create a new array by traversing the first to copy it, and then traverse the second to push(most complex). a[name].push(e) && a[name] will push onto the array and then return it(least complex). All three have slightly different complexity– Robert Mennell
yesterday
1
1
Oh, you're talking about time complexity/efficiency--I thought you were talking readability. That's fair enough.
– ggorlen
yesterday
Oh, you're talking about time complexity/efficiency--I thought you were talking readability. That's fair enough.
– ggorlen
yesterday
add a comment |
JavaScript has several built in
Array.prototypemethods for traverse and transforming arrays. More information can be found at the MDN for Arrays developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…– Robert Mennell
yesterday
Also in JavaScript we just access them using the bracket notation:
object[key]orobject.keyif the key is known. As for making a new object, object literals are allowed to use computed values{ [key] : value }and more information can be found here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…– Robert Mennell
yesterday
The Python code you posted does not have a "dict comprehension". You are iterating in a conventional
forloop and then building yourservicesdictionary. With Javascript, the most appropriate array method for this case seems likereduce.– slider
yesterday
I don't see how this relates to dict comprehension as your Python snippet does not use it. Python dict comprehension looks like
{ key: value for key, value in iterable }– trincot
yesterday
Shouldn't your result include
{"service": "service2", "perfData": "unique string1", "state": 1}in theserver2key?– ggorlen
yesterday