I have an object like below. Trying to rearrange it in ascending order based on value. Similar to Javascript array sort method.
var masterList = {
"1": "google",
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay"
}
Please let me know the better solution...
JavaScript objects have no order. Even though most browsers do iterate in the same order the properties were created, there's no guarantee, so sorting is not supported on objects.
See here for more info: Does JavaScript Guarantee Object Property Order?
You might also be interested in what John Resig has got to say on the matter.
If you need a sort-able list, you'll have to store it as an array of objects:
var masterList = [
{ key: 1, val: "google" },
{ key: 2, val: "yahoo" },
{ key: 3, val: "msn" },
{ key: 4, val: "stackoverflow" },
{ key: 5, val: "github" },
{ key: 6, val: "jsfiddle" },
{ key: 7, val: "amazon" },
{ key: 8, val: "ebay" }
];
Then, to sort them, just use the regular array's sort method:
masterList = masterList.sort(function (a, b) {
return a.val.localeCompare( b.val );
});
Here's the fiddle: http://jsfiddle.net/ASrUD/
var obj = {
"1": "google",
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay"
};
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
alert(arr.sort());
This will sort your values in ascending order. let me give sometime will revert you with how to convert that to an object.
var masterList = {
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay",
"1": "google",
}
var masterList_ = {}
Object.keys(masterList).sort().forEach(a=>masterList_[a]=masterList[a])
console.log(masterList_)
Related
I have response from the sarver like this :
{
"response_code": 200,
"tickets": {
"3": {
"117": "http://....../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"4": {
"118": "http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"5": {
"119": "http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"6": {
"120": "http://.../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
"7": {
"121": ""
},
"8": {
"122": "http://..../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"
},
}
}
}
and I should display these links in the websites as it should be an array, but it's an array
so any clue how can I display these links in react app, or how can I convert it to array, so I can display it easily?
If you just want to convert the tickets object to an array of URLs (ignoring any of those number keys), you can do so using Object.values() and Array.prototype.flatMap()
const obj = {"response_code":200,"tickets":{"3":{"117":"http://....../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"4":{"118":"http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"5":{"119":"http://...../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"6":{"120":"http://.../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"},"7":{"121":""},"8":{"122":"http://..../upload/iblock/4a5/4a529553152b21109e9aa18fa9d4ea9b.pdf"}}}
const tickets = Object.values(obj.tickets).flatMap(Object.values)
console.log(tickets)
I have object like this
const Obj =
"Value1": {
"value1value": "1"
},
"Value2": {
"value2value": "2"
},
"Value3": {
"value3value": "3"
},
"BTest": {
"1": "1",
"2": "2"
},
"Value4": {
"value4value": "value4value"
},
"ATest": {
"1": "1",
"2": "2"
},
"Value5": {
"value5value": "value5value",
"value6value": "value6value"
},
"TestA": {
"1": "1",
"2": "2"
};
What i need is to create new object that will look like this
cont newObject =
"Value1": {
"value1value": "1"
},
"Value2": {
"value2value": "2"
},
"Value3": {
"value3value": "3"
},
"Value4": {
"value4value": "value4value"
},
"Value5": {
"value5value": "value5value",
"value6value": "value6value"
};
Some values are removed, i have tried with like
const newObject = Obj.map(o => {
return { };
});
But i had no luck, does somebody knows what has to be done, thanks in advance
Looks like you want to extract keys which starts with specific value so you can do something like
var obj={"Value1": {
"value1value": "1"
},
"Value2": {
"value2value": "2"
},
"Value3": {
"value3value": "3"
},
"BTest": {
"1": "1",
"2": "2"
},
"Value4": {
"value4value": "value4value"
},
"ATest": {
"1": "1",
"2": "2"
},
"Value5": {
"value5value": "value5value",
"value6value": "value6value"
},
"TestA": {
"1": "1",
"2": "2"
}}
let newObj={};
Object.keys(obj).forEach(k=>{
if(k.startsWith('Value')){
newObj[k]=obj[k];
}
})
console.log(newObj)
If you do not want to use startwith etc and want to use full names how about this, You create an array with the names that you want to remove and than simply check add keys that are not in that array to new object. Something like this
const removeableItems = ["TestA", "BTest", "ATest"]
let newObj = {}
for (var key in obj) {
if (obj.hasOwnProperty(key) && !removeableItems.includes(key)) {
newObj[key] = obj[key];
}
}
Here is a blitz showing this.
You can use Object.assign() and Spread syntax combined with Object.keys(), Array.prototype.filter(), Array.prototype.map() and String.prototype.startsWith():
const Obj = {"Value1": {"value1value": "1"},"Value2": {"value2value": "2"},"Value3": {"value3value": "3"},"BTest": {"1": "1","2": "2"},"Value4": {"value4value": "value4value"},"ATest": {"1": "1","2": "2"},"Value5": {"value5value": "value5value","value6value": "value6value"},"TestA": {"1": "1","2": "2"}};
const result = Object.assign(
{},
...Object.keys(Obj)
.filter(k => k.startsWith('Value'))
.map(k => ({ [k]: Obj[k] }))
);
console.log(result);
Can anyone explain why the final output is the same in different uses of array.reduce() function?
In the first instance, the sample array is reduced directly whereas, in the second example, the sample array is first reversed and then reduced.
var array = [{
"Id": "1",
"Week": "2019-01-13"
},
{
"Id": "2",
"Week": "2019-01-20"
},
{
"Id": "3",
"Week": "2019-01-27"
}
];
array.reduce(function (acc, curr) {
acc[curr.Id] = curr.Week;
console.log(acc);
return acc;
}, {});
//Output
/*{ "1": "2019-01-13" }
{ "1": "2019-01-13", "2": "2019-01-20" }
{ "1": "2019-01-13", "2": "2019-01-20", "3": "2019-01-27" }*/
array.reverse().reduce(function (acc, curr) {
acc[curr.Id] = curr.Week;
console.log(acc);
return acc;
}, {});
//Output
/*{ "3": "2019-01-27" }
{ "2": "2019-01-20", "3": "2019-01-27" }
{ "1": "2019-01-13", "2": "2019-01-20", "3": "2019-01-27" }
*/
I would like the output to appear as
{ "3": "2019-01-27", "2": "2019-01-20", "1": "2019-01-13" }.
If I use non numeric keys, the reduce function output in both scenarios are as expected(in the same order elements are passed).
As already mentioned in the comments object prop order is not guaranteed in JS which is why you get that output. If you want order to matter you need to use Map as your reduce accumulator.
The Map object holds key-value pairs and remembers the original
insertion order of the keys.
With that said here is some sample code to illustrate it better:
var array = [{ "Id": "1", "Week": "2019-01-13" }, { "Id": "2", "Week": "2019-01-20" }, { "Id": "3", "Week": "2019-01-27" } ];
let r1 = array.reduce(function(acc, curr) {
acc.set(curr.Id, curr.Week);
return acc;
}, new Map());
let r2 = array.reverse().reduce(function(acc, curr) {
acc.set(curr.Id, curr.Week);
return acc;
}, new Map());
console.log('r1:')
r1.forEach(x => console.log(x))
console.log('r2:')
r2.forEach(x => console.log(x))
console.log('fromEntries:')
console.log(Object.fromEntries(r1))
console.log(Object.fromEntries(r2))
Notice how the order is different when we loop through the entries of the two maps (r1 & r2). Also notice however that the moment you convert the maps to object literals the order is now the same since JS prop order is not guaranteed.
[null, {
"display_with": "7",
"id": "1",
"image": "/images/salt_sugar.png",
"name": "Salt and Sugar",
"subcategories": {
"1": true,
"6": true,
"7": true
}
}, {
"display_with": "6",
"id": "2",
"image": "/images/tea_and_coffee.png",
"name": "Tea and Coffee",
"subcategories": {
"8": true,
"9": true,
"124": true
}
}]
In the above string i want 1, 6, 7 and 8, 9, 124 from second and third record respectively.
This is my logic.
recvCategories = JSON STRING
for (var j=0; j<recvCategories.length; ++j){
var category = recvCategories[j];
if (category != undefined){
var subcategories = [];
int size = Object.keys(category.subcategories).length;
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
}
}
How to print 1, 6, 7 and 8, 9, 124 in // do stuff ??
Assuming your data is named data this should do it.
var keys = [];
data.forEach(d => {
if (d.subcategories)
for (var key in d.subcategories)
keys.push(key);
})
It may look simple however by using a for(var x in y) will actually iterate the properties of an object and return the propertyNames.
So in the example we call the .forEach() method in an array and then iterate each key of subcategories pushing them into a new array.
Something like,
for( i in aList) {
console.log(keys(aList[i] && aList[i].subcategories))
}
// []
// [1, 6, 7]
// [8, 9, 124]
Few pointers in your code:
This condition: if (category != undefined) will not validate null and code will throw on object.something
Object.keys(category.subcategories).length; will break if you do not have property subcategories in object. You can try something like this (Object.keys(category.subcategories) || []).length
Also if you create your own custom object, then it makes sense to use object.hasOwnProperty, but if you are reading form JSON, you can rely on Object.keys
You can also try something like this:
function getSubCategoriesKeys(d){
return d.reduce(function(p,c){
if(!isEmpty(c) && typeof(c) === "object" && c.hasOwnProperty("subcategories")){
p = p.concat(Object.keys(c.subcategories))
}
return p;
}, [])
}
function isEmpty(o){
return o === undefined || o === null || o.toString().trim().length === 0
}
var data = [null, {
"display_with": "7",
"id": "1",
"image": "/images/salt_sugar.png",
"name": "Salt and Sugar",
"subcategories": {
"1": true,
"6": true,
"7": true
}
}, {
"display_with": "6",
"id": "2",
"image": "/images/tea_and_coffee.png",
"name": "Tea and Coffee",
"subcategories": {
"8": true,
"9": true,
"124": true
}
}]
var keys = getSubCategoriesKeys(data);
console.log(keys)
Reference
what is property in hasownproperty
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
How do I pull out ColumnValues[i] using javascript from this JSON sample using two instances with keys = "1" and "2" as shown below. This is just a sample my original JSON object has 500+ entries like this with key = "1", "2", "3", "4", etc. When I retrieve the length of the object the value that is returned equals 1 so using for loop does not work with the length property. Appreciate any help.
JSON object below
[
{
"1": {
"ChildCount": 0,
"ColumnIndentLevel": 0,
"DescendantCount": 0,
"IndentLevel": 0,
"IsCategory": false,
"IsConflict": false,
"IsDocument": true,
"IsTotal": false,
"IsValid": true,
"NoteID": "3962",
"SiblingCount": 2,
"UniversalID": "E8D5D7E88B08CBD686257CD6007470E5",
"ColumnValues": {
"0": "03297",
"1": "Amelia Tang",
"2": "NBK3456",
"3": "FHA",
"4": "2008/10/03 00:00:00 UTC-0000",
"5": "Withdrawn by SASE Administration",
"6": "Approver Level 2",
"7": "Reinstatement"
}
},
"2": {
"ChildCount": 0,
"ColumnIndentLevel": 0,
"DescendantCount": 0,
"IndentLevel": 0,
"IsCategory": false,
"IsConflict": false,
"IsDocument": true,
"IsTotal": false,
"IsValid": true,
"NoteID": "7972",
"SiblingCount": 2,
"UniversalID": "4CEE012B8D60A86A86257CD6007657B0",
"ColumnValues": {
"0": "20004484",
"1": "Anthony Susino",
"2": "",
"3": "Conventional",
"4": "2009/05/11 00:00:00 UTC-0000",
"5": "Withdrawn by SASE Administration",
"6": "",
"7": ""
}
}
}]
Use this:
for (var key in yourObject) { // key will be "1", "2", ...
var value = yourObject[key];
// do something
}
var ColumnValues = /* that object */,
i = 0; //this makes sure the object is iterated in an ascending order
while(i++ in ColumnValuesd){ //and ignores irrelevant properties that are
var item = ColumnValues[i]; //inherited from Object's prototype.
//do something
}
Same goes for the most-top level keys.