sort javascript numbered keys object by property values [duplicate] - javascript

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 5 years ago.
I want to sort following object by Value
var myObj = {"1": {"Value": 40}, "2": {"Value": 10}, "3": {"Value": 30}, "4": {"Value": 20}};
I tried to use sort to get keys of desired order but while making new object using it is the problem for me. I tried below method to sort:
var myObj = {"1": {"Value": 40}, "2": {"Value": 10}, "3": {"Value": 30}, "4": {"Value": 20}};
sorted = Object.keys(myObj).sort((a,b) => myObj[a].Value - myObj[b].Value).reduce((_sortedObj, key) => ({
..._sortedObj,
[key]: myObj[key]
}), {});
console.log(sorted);
Can somebody point out where am I making mistake?

Javascript Objects are not Ordered like arrays. They are key value
pairs and you can access any value in constant time by just it's key.
If you want them to be ordered then you can iterate over the properties of your object and push them in array and sort them in the order you want.
you can get something like this.
[{"Value": 10}, {"Value": 20}, {"Value": 30}, {"Value": 40}];
This is an array of Objects where each element is an object containing a key-value pair.

Related

JavaScript Array of Objects to Array of Arrays Grouped by Object Prop Value [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed 2 years ago.
This is somewhat complex for me to put into words properly, so I'll just drop an example of what I'm trying to do in terms of input and expected output below. I've tried a few things but they seem to be way more complex than needed, result in duplication issues, or flat out don't work. Thanks ahead of time for any help people can provide. And if there's already a post that answers this question, I am sorry and I'll gladly take that link - as I said, it's difficult to put this into words.
Input: Array of Objects
Ex:
[
{prop: 1},
{prop: 1},
{prop: 2},
{prop: 3},
{prop: 2}
]
OUTPUT: Array of arrays where all objects with some matching property are grouped.
Ex:
[
[{prop: 1}, {prop: 1}],
[{prop: 2},{prop:2}],
[{prop:3}]
]
Simple reduce loop with an object
var arr = [
{prop: 1},
{prop: 1},
{prop: 2},
{prop: 3},
{prop: 2}
]
const result = Object.values(arr.reduce((acc, item) => {
acc[item.prop] = acc[item.prop] || [];
acc[item.prop].push(item);
return acc;
}, {}));
console.log(result);

Change key name in an array of objects based on value from first element array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have raw json from file .csv like
[{
"A": "CustomerCode",
"B": "Country",
"C": "CountryCode"
},
{
"A": "C101",
"B": "AUS",
"C": "AUS01",
},
{
"A": "C102",
"B": "AUS",
"C": "AUS02",
}]
How can I could remove first element of array and change key name of array object like that
[{
"CustomerCode": "C101",
"Country": "AUS",
"CountryCode": "AUS01",
},
{
"CustomerCode": "C102",
"Country": "AUS",
"CountryCode": "AUS02",
}]
You could use .map() with Object.entries() and Object.fromEntries() to create new objects with keys from the first object in your array like so:
const arr = [{A:"CustomerCode",B:"Country",C:"CountryCode"},{A:"C101",B:"AUS",C:"AUS01"},{A:"C102",B:"AUS",C:"AUS02"}];
const prop_map = arr.shift();
const res = arr.map(o =>
Object.fromEntries(
Object.entries(o).map(([k, v]) => [prop_map[k], v]))
);
console.log(res);
Above, .shift() gets the first object from the array as a mapping object to reference later. The .map() is then in charge of mapping (ie converting) each object to a new modified object. The new modified object is defined by what the internal function of .map() returns. In this can it takes the entries (a key-value pair array [[key, value]]) of objects and uses another .map() method. This .map() maps each key-value pair array to a new key-value pair array. However, the key now is defined by its associated value in the prop_map (the object we extracted at the beginning using .shift()). Now that we have an array of key-value pair arrays where each key is a value from the prop_map, we can use Object.fromEntries(), which converts this key-value pair array into an object. This new object is returned by the .map() being applied to the arr, which produces the final result.
Do note that Object.fromEntries() does have limited browser compatibility, however, you can use a polyfill if need be.
You can remove the first item from the array then map over the array.
let data = [{
"A": "CustomerCode",
"B": "Country",
"C": "CountryCode"
},
{
"A": "C101",
"B": "AUS",
"C": "AUS01",
},
{
"A": "C102",
"B": "AUS",
"C": "AUS02",
}];
// Remove first item in array
data.shift();
let newData = data.map(({A, B, C}) => ({
CustomerCode: A,
Country: B,
CountryCode: C
}));
console.log(newData);

(javascript) Get all object keys from array of objects with dynamic properties [duplicate]

This question already has answers here:
Getting JavaScript object key list
(19 answers)
Closed 5 years ago.
What's the easiest way to get object keys from array of objects.
Ex.
var obj = [{"foo": 1, "bar": 2}, {"foo": 10, "bar": 20, "baz": 30}]
// ['foo', 'bar', 'baz']
You can map everything to a single array with reduce:
obj.reduce((acc, curr) => acc.concact(Object.keys(curr)), [])
This gives you:
['foo', 'bar', 'foo', 'bar', 'baz']

Reading CSV in D3 and converting it to array of arrays

I have the following small dataset hardcoded into a variable in my code:
var dataset = [['CENTRAL', 44, 552, 18565],
['NORTHERN', 42, 945, 20092],
['SOUTHERN', 96, 795, 30095],
['PARK', 1, 640, 9341],
['MISSION', 66, 1198, 18542],
['TENDERLOIN', 23, 113, 10735],
['RICHMOND', 9, 561, 9082],
['TARAVAL', 81, 789, 11966],
['INGLESIDE', 5, 1368, 13414],
['BAYVIEW', 7, 985, 14711]];
Now, this dataset is taken directly from a .csv file, that looks like this:
District,Prostitution,VehicleTheft,Totalcrimecount
CENTRAL,44,552,18565
NORTHERN,42,945,20092
SOUTHERN,96,795,30095
PARK,1,640,9341
MISSION,66,1198,18542
TENDERLOIN,23,113,10735
RICHMOND,9,561,9082
TARAVAL,81,789,11966
INGLESIDE,5,1368,13414
BAYVIEW,7,985,14711
However, I'd obviously like to be able to just read in the file, which I've attempted using this:
var dataset_csv = d3.csv("datafile.csv", function(d){
console.log(dataset_csv = d)
});
Which gives me an array of objects that look like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
District: "CENTRAL"
Prostitution: "44"
Totalcrimecount: "18565"
VehicleTheft: "552"
My question is, and it might be trivial, how can I transform those objects into an array data structure like my initial dataset? I've been battling with it for some time now. Any hints greatly appreciated.
Use Array#map to iterate over each object and Object.keys to catch only the keys values.
var dataset_csv = [{District: "CENTRAL", Prostitution: "44", Totalcrimecount: "18565", VehicleTheft: "552"}, {District: "WEST", Prostitution: "22", Totalcrimecount: "4324", VehicleTheft: "53"}, {District: "EAST", Prostitution: "11", Totalcrimecount: "23434" , VehicleTheft: "76"}],
datasetArr = dataset_csv.map(v => Object.keys(v).map(c => Number(v[c]) ? Number(v[c]) : v[c]));
console.log(datasetArr);

Problem of serializing javascript object to JSON string

My question is sort of stupid that why
JSON.stringify({"annotation": [{"x":1, "y":2}, {"x":1, "y":2}]})
does not return
{"annotation": [{"x": 1, "y": 2}, {"x": 1, "y": 2}]}
but returns
{"annotation":"[{\"x\": 1, \"y\": 2}, {\"x\": 1, \"y\": 2}]"}
and how can I get the first output?
Are you using Prototype? This question may be related:
JSON.stringify() array bizarreness with Prototype.js

Categories