node.js - Sort JSON objects by a value [duplicate] - javascript

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 5 years ago.
I have this JSON file on my server:
{"1504929411112":{"name":"user1","score":"10"},"1504929416574":{"name":"2nduser","score":"14"},"1504929754610":{"name":"usr3","score":"99"},"1504929762722":{"name":"userfour","score":"40"},"1504929772310":{"name":"user5","score":"7"}}
Assuming I have parsed this file:
var json = JSON.parse(getJSONFile());
How can I now sort each object in the json variable by the score property?
None of the array sorting functions work for me as json is not an array.

Since these are objects' properties, their order is usually unknown and not guaranteed. To sort them by some internal property, you would first have to change the Object into an Array, for example:
const json = JSON.parse(getJsonFile());
const jsonAsArray = Object.keys(json).map(function (key) {
return json[key];
})
.sort(function (itemA, itemB) {
return itemA.score < itemB.score;
});
For more, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var ob = { "fff": { "name": "user1", "score": "10" }, "bbbb": { "name": "user4", "score": "14" }, "dddd": { "name": "user2", "score": "99" }, "cccc": { "name": "user5", "score": "40" }, "aaaa": { "name": "user3", "score": "7" } };
Object.keys(ob).map(key => ({ key: key, value: ob[key] })).sort((first, second) => (first.value.name < second.value.name) ? -1 : (first.value.name > second.value.name) ? 1 : 0 ).forEach((sortedData) => console.log(JSON.stringify(sortedData)));

Related

How to convert value into key & another key into value in JavaScript [duplicate]

This question already has answers here:
How to convert array of key–value objects to array of objects with a single property?
(5 answers)
Closed 1 year ago.
This is my array of Object. I want to convert my first value into key & Second value into value only. Please go through question and i have also attached my desired output.
[
{
"name": "Unknown",
"value": "RAHUL"
},
{
"name": "FirstName",
"value": "WILLEKE LISELOTTE"
},
{
"name": "LastName",
"value": "DE BRUIJN"
}
]
I want my Object as
{
"Unknown": "RAHUL"
},
{
"FirstName": "WILLEKE LISELOTTE"
},
{
"LastName": "DE BRUIJN"
}
IF you mean to create a new array, then simply map the original array. You don't need to create a new array and push into it, that's just redundant code:
const testData = [{
"name": "Unknown",
"value": "RAHUL"
},
{
"name": "FirstName",
"value": "WILLEKE LISELOTTE"
},
{
"name": "LastName",
"value": "DE BRUIJN"
}
];
const newData = testData.map(nameObject => {
return {
[nameObject.name]: nameObject.value
}
});
console.log(newData);
You just have to use brackets for [value.name] to perform achieve this.
var arr = []
testdata.map((value) => {
arr.push({ [value.name]: value.value })
})

filter array by its name inside an object [duplicate]

This question already has an answer here:
JS Calling Object Property by Variable
(1 answer)
Closed 2 years ago.
var dictionary = {
"english" : [{"key" : "1", "value" : "abc"}],
"french" : [[{"key" : "1", "value" : "xyz"}]]
}
if I do this filter it is working :
dictionary.english.filter ( obj => {return obj.value === "abc"})
but if mention the array name english in a variable and use the same filter it shows me undefined:
var language = 'english';
dictionary.language .filter ( obj => {return obj.value === "abc"})
what is the difference and how to fix it?
Try this
var dictionary = {
"english": [{
"key": "1",
"value": "abc"
}],
"french": [
[{
"key": "1",
"value": "xyz"
}]
]
}
var language = 'english';
let _d = dictionary[language].filter(obj => {
return obj.value === "abc"
})
console.log(_d)

Filter array based property value [duplicate]

This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 3 years ago.
I have a JSON file containing 13k objects. I need to get only the objects which have the events { name: "Submitted"} property from it. events is an array of objects which contain multiple name properties. Here is a screenshot of how it looks:
{
"_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
"_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
"doctype": "application",
"events": [{
"name": "change",
"time": 1532547503182
},
{
"name": "change",
"time": 1532547503182
},
{
"name": "submitted",
"time": 1532547503182
},
{
"name": "edited",
"time": 1532547503182
}
]
}
This is how I get all the object inside the json file:
$.getJSON("export.json", function(data) {
var data = [];
var arrays = data;
var i;
for (i = 0; i < arrays.length; i++) {
console.log(arrays[i]);
}
});
Now I need to push all the objects which have events[name:submitted] I get in arrays[i] into the doc[]. How can I filter the results?
You can filter your array of the object by filter method.
$.getJSON("export.json", function(data) {
var data = [];
var arrays = data;
var newArray = arrays.filter(function (el) {
return el.name == 'Submitted';
});
console.log(newArray);
});
You can also do in one line using ES6 arrow function
var newArray = arrays.filter(el => el.name === 'Submitted')
You can use filter(), checking each element in the events array to see if the name is equal to submitted:
const object = {
"_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
"_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
"doctype": "application",
"events": [{
"name": "change",
"time": 1532547503182
},
{
"name": "change",
"time": 1532547503182
},
{
"name": "submitted",
"time": 1532547503182
},
{
"name": "edited",
"time": 1532547503182
}
]
}
const filtered = object.events.filter(obj => obj.name === 'submitted')
console.log(filtered)

Convert an array of object to the array of string in TypeScript [duplicate]

This question already has answers here:
Accessing properties of an array of objects [duplicate]
(5 answers)
Closed 5 years ago.
Using lodash I need to convert an array of object to the array of string.
Original array,
const tags = [{
"display": "tag1",
"value": "tag1"
}, {
"display": "tag2",
"value": "tag2"
}]
Expected result,
const tags = ["tag1", "tag2"]
I tried this way,
const data = [{
"display": "tag1",
"value": "tag1"
}, {
"display": "tag2",
"value": "tag2"
}]
const result = _(data)
.flatMap(_.values)
.map((item) => { if (typeof item === 'string') { return item; } else { return; } })
.value()
console.log('result', result);
You dont need lodash, you can do with plain JS using map
DEMO
const tags = [{
"display": "tag1",
"value": "tag1"
}, {
"display": "tag2",
"value": "tag2"
}]
var result = tags.map(a => a.display);
console.log(result);

Filter an array of object by object content [duplicate]

This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 6 years ago.
I am trying to filter an array of objects by its content, i.e.:
https://jsfiddle.net/z7g3unyu/2/
var arr =[
{
"uid": "1",
"name": "John Doe"
},
{
"uid": "2",
"name": "Kate Roe"
}
];
var newArr = arr.filter(function(e) {
return e["uid"] == 1;
});
alert(newArr["name"]);
I wanted to create a new array that contains only one object which uid is equal to 1. However, it gives me undefined. What am I doing wrong?
Here you assign the value:
return e["uid"] = 1;
Use double equals == to check the value for equality:
return e["uid"] == 1;
Note that filter() returns array, not object. Use brackets notation [0] to get first element from an array.
See working snippet below
var arr = [{
"uid": "1",
"name": "John Doe"
}, {
"uid": "2",
"name": "Kate Roe"
}];
var newArr = arr.filter(function(e) {
return e["uid"] == 1;
});
alert(newArr[0]["name"]);
Using Lodash
_.filter(array, { uid: 1 });

Categories

Resources