How to remove space in keys of a JSON object - javascript

I have an output like below:
output = {
"New Classroom": [{
"Name": "Apple",
"Age": "6",
"Percentage": "24.00%"
}, {
"Name": "Orange",
"Age": "5",
"Percentage": "9.88%"
}, {
"Name": "Green",
"Age": "2",
"Percentage": "27.27%"
}, {
"Name": "Grey",
"Age": "6",
"Percentage": "12.63%"
}]
}
How do I replace New Classroom with NewClassroom and the New classroom is not always a "NewClassroom".It may be different text
ob = JSON.parse(output);
alert(Object.keys(ob))
when I do this, I'm getting Newclassroom as the key

You can loop through the top-level property names in the object you receive, detect any with spaces, and remove the spaces. (You don't need to, they're perfectly valid property names, but you can if you want.)
var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]};
var name, newName;
// Loop through the property names
for (var name in output) {
// Get the name without spaces
newName = name.replace(/ /g, "");
// If that's different...
if (newName != name) {
// Create the new property
output[newName] = output[name];
// Delete the old one
delete output[name];
}
}
console.log(output);
Note that using delete on an object can reduce the performance of subsequent property lookups. 99.99% of the time, that doesn't matter. If it matters in your case, create a new object rather than modifying it in place:
var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]};
var name, newName;
var newOutput = {};
// Loop through the property names
for (var name in output) {
// Get the name without spaces
newName = name.replace(/ /g, "");
// Copy the property over
newOutput[newName] = output[name];
}
console.log(newOutput);

Use Object.keys to get all keys of the object
Use String#replace to replace character from String
var obj = {
"New Classroom": [{
"Name": "Apple",
"Age": "6",
"Percentage": "24.00%"
}, {
"Name": "Orange",
"Age": "5",
"Percentage": "9.88%"
}, {
"Name": "Green",
"Age": "2",
"Percentage": "27.27%"
}, {
"Name": "Grey",
"Age": "6",
"Percentage": "12.63%"
}]
};
Object.keys(obj).forEach(function(key) {
var replaced = key.replace(' ', '');
if (key !== replaced) {
obj[replaced] = obj[key];
delete obj[key];
}
});
console.log(obj);
Note: Only single occurrence of space is considered, RegEx could be used if space occurrence is more than once!

Loop in each keys of the json, then parse.
try regexp
var word = "New Classroom"
word = word.replace(/\s/g, '');
console.log(word)

Related

How to resolve error: "undefined" when reading single values from JSON using JavaScript?

I have a JavaScript function that outputs all values from a JSON file to a Terminal, but when attempting to print a single value, I get the following error: Line 74 - Cannot read properties of undefined (reading 'width')
Here is the code:
var json = `{
"columns": [{
"fname": "John",
"lname": "Doe",
"age": "23"
},
{
"fname": "Jane",
"lname": "Doe",
"age": ""
},
{
"fname": "Tom",
"lname": "Johns",
"age": ""
},
{
"fname": "Brian",
"lname": "Wicks",
"age": "27"
},
{
"fname": "Tim",
"lname": "Stone",
"age": ""
},
{
"fname": "Fred",
"lname": "Wilson",
"age": ""
},
{
"fname": "Jason",
"lname": "Voorhees",
"age": "90"
}
],
"rows": [{
"data": {
"width": "2",
"height": "7",
"length": "",
"finalresult": "44",
"firstresult": "",
"secondresult": "300.00",
"thirdresult": "700.40"
}
}]
}`;
var obj = JSON.parse(json);
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
console.log(obj[k] + "\n");
};
}
};
// Printing all the values from the resulting object
printValues(obj);
//print single value
//console.log(obj["columns"]["rows"]["data"]["width"] + "\n");
console.log("Print Indiviual values:");
console.log(obj["rows"]["data"]["width"] + "\n"); //The Error
...Could I get some assistance as to what I'm doing wrong? ...Thanks
As #Yarin and #codemonkey pointed out—you're trying to access the data object as a direct object property of rows, e.g. obj.rows.data which is wrong and will return undefined because data is not a property of the rows object. Instead it's the first (and only) entry in the array of objects that is rows.
You need to either change the syntax to:
obj.rows[0].data.width
Or take the data object out of the array and remove the array so that the rows object is structured like this:
const obj = {
rows: {
data: {
width: 1
}
}
}
// Then you can use this syntax...
console.log( obj.rows.data.width )
// or even this syntax if you want to...
console.log( obj['rows']['data']['width'] )
I see that the width is the property of object data that is inside array rows...

How to remove duplicates in array by choosing which one to keep? [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
The problem
I have a Javascript array that can contains duplicates (only 2) having same value for the key color.
var array = [
{
"id": "1",
"color": "red",
"animal": null
},
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
I'd like to remove duplicates on key color and only keep the unique object having the key animal not null.
var uniqueArray = [
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
What I tried
var obj = {};
for (var i = 0; i < array.length; i++) {
obj[array[i]['name']] = array[i];
}
var uniqueArray = new Array();
for (var key in obj) {
uniqueArray.push(obj[key]);
}
Here's the result :
var uniqueArray = [
{
"id": "1",
"color": "red",
"animal": "null"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
I don't know how to choose which object I want to keep.
Note : I can't use ES6
I hope the value of animal should be null instead of 'nul' in the first.
var array = [
{
"id": "1",
"color": "red",
"animal": null
},
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
If you want to pick the unique values(objects in this case) based on color,it's better to create another object and put color as a key to get the unique values.
var obj = {};
array.forEach(a => {
if(!obj[a.color] && a.animal) {
obj[a.color] = a;
}
});
Now the object looks like following
Now you get an object containing unique object based on color and more importantly your animal property is not null.
You said you can't think of what to choose here.
IMO it's better to select the one having a value rather than a null value.
NOTE: the above code gives you an object but you can convert it to an array easily by following. Not entirely sure if Object.values is an es6 feature or not(didn't find anything on docs).
var arr = Object.values(obj);
If you don't like the above solution, you can iterate over the object and push it to an array.
var finalArr = [];
Object.keys(obj).forEach(function(key) {
finalArr.push(obj[key])
});
Just remove all the null values with a simple filter:
var array = [{"id":"1","color":"red","animal":"cat"},{"id":"2","color":"red","animal":"null"},{"id":"3","color":"green","animal":"dog"},{"animal":"dog"}];
var uniqueArray = array.filter(function(e) {
return e.animal != "null";
});
console.log(uniqueArray);
Without using ES6
var array = [{
"id": "1",
"color": "red",
"animal": "cat"
},
{
"id": "2",
"color": "red",
"animal": "null"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
var a = [];
var arr = [];
array.forEach(function(e, i) {
if (a.indexOf(e.color) == -1 && e.animal != "null") {
a.push(e.color)
arr.push(e)
}
})
console.log(arr)

Compare array of objects to array of ids

Using jQuery, I would like to use an array of ids to find the objects inside the allObjects array that have the matching Id value.
var arrayOfIds = [1, 4, 5];
var allObjects = [{"Id":"1", "name":"aa"},{"Id":"2", "name":"bb"} ,{"Id":"3", "name":"cc"} ,{"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}, {"Id":"6", "name":"ff"}, {"Id":"7", "name":"gg"}, {"Id":"8", "name":"hh"}, {"Id":"9", "name":"ii"}];
The result would equal:
[{"Id":"1", "name":"aa"}, {"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}]
So far, I can only use the following to extract an individual object:
var result = $.grep(arrayOfIds, function(e) { return e.Id == 3; });
I feel as though the answer might be achieved by amending the above $.grep query somehow but can't figure it out.
You don't need jQuery for this. You can use Array.prototype.filter() to filter allObjects and Array.prototype.includes() to check if the objects Id property is in arrayOfIds:
allObjects.filter(x=> arrayOfIds.includes(Number(x.Id)))
See demo on JS Bin.
Best is you transform the array to an object itself:
function atoo(a)
{
var i, obj;
obj = {};
for (i = 0; i < a.length; i++)
{
obj[a[i].Id] = a[i];
}
return obj;
}
You can now access all items in the array through the object by simply addressing them as an index:
obj["4"]
returns the correct object that is also stored in the array under a[3].
There is no jQuery involved which should be considered a feature because it is a general solution to all kinds of these problems.
Using a filter (as in Array.prototype.filter()) is easier to write but also incurs in performance problems when you access the items very often or the array is very large. The above solution relies on the internal implementation of the object referencing which is as fast as you can wish for.
You can use filter() method like following.
var arrayOfIds = [1, 4, 5];
var allObjects = [{ "Id": "1", "name": "aa" }, { "Id": "2", "name": "bb" }, { "Id": "3", "name": "cc" }, { "Id": "4", "name": "dd" }, { "Id": "5", "name": "ee" }, { "Id": "6", "name": "ff" }, { "Id": "7", "name": "gg" }, { "Id": "8", "name": "hh" }, { "Id": "9", "name": "ii" }];
var result = $(allObjects).filter(function() { return arrayOfIds.indexOf(+this.Id) > -1 }).get();

AngularJS search filter in array into object

I look ID in an array of objects JSON.
Example JSON:
{
"Przydzial": [{
"M": "Cos",
"Przydzialt": [{
"Name": "",
"Przydz": "tach_1",
"Cos": "Pod",
"Ha": "20",
"ID": "94"
}, {
"Name": "B_K",
"Przydz": "lea",
"Cos": "Chea",
"HA": "8",
"ID": "78"
}
}]
}]
}
Use in controller
var foo = { //my json };
var nowy = $filter('filter')(foo.Przydzialt, { ID:78});
result:
console.log(nowy); // undefined
json is correct - validated in JSLint.
As "$foo.Przydzial" is an array of objects, where every object has its "Przydzialt" attribute, you should execute $filter in a loop:
var newArray;
angular.forEach($foo.Przydzial, function (el) {
newArray = $filter('filter')(el.Przydzialt, {ID: 78});
console.log(newArray);
});

Is this valid json data?

The url has following json data:
[{ "topic": "cricket",
"value": "Player [ playerid=123, category=b, high=150, total=2300]",
"place": "xyz"},
{ "topic": "cricket",
"value": "Player [ playerid=456, category=c, high=60, total=300]",
"place": "abc"},
{ "topic": "cricket",
"value": "Player [ playerid=789, category=a, high=178, total=5300]",
"place": "bnm"}]
I tried online to check whether this is valid json or not through following link: http://jsonformatter.curiousconcept.com/ it says valid. if it is, how do I access each playerid ?
It is valid JSON, but the data about the player is embedded in a random string. You can do one of two things:
Update the service to send back a different, valid JS value, for example:
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
}
Parse the data in the value key yourself:
// Simple regex, not really "parsing"
var playerIdRE = /playerid=(\d+)/i;
var result = playerIdRE.exec(yourData[0].value);
// result[0] is the full match, while result[1] is the ID.
// Or the more complicated version that does full parsing
var format = /\s*(.*?)\s*\[\s*([^\]]+)\s*\]\s*/gi,
keyValuePair = /(\w+)=([^,\]]*),?\s*/gi
function parseComplexDataType(input) {
var result = format.exec(input),
typeName = result[1],
keyValues = result[2],
returnValue = {};
if (!typeName) return returnValue;
returnValue.typeName = typeName;
input.replace(keyValuePair, function(_, key, value) {
returnValue[key] = value;
});
return returnValue;
}
// Usage:
> parseComplexDataType("Player [ playerid=123, category=b, high=150, total=2300]")
Object {typeName: "Player", playerid: "123", category: "b", high: "150", total: "2300"}
For your purposes, it is not valid. Once the JSON is corrected, you simply need to loop through the array and read each value.
var jArray = [{
"topic": "cricket",
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
},
"place": "xyz"
}, {
...
}]
To access the JSON data ...
for (var i=0,len=jArray.length; i<len; i++) {
console.log(jArray[i].topic, jArray[i].value.type);
}
Yes, it is. I check it via: http://jsonlint.com/
Extracting "playerid":
Initialise the string to JSONArray.
Iterate over each element in the above array.
Now, from each element extract "value".
Finally, from this string you can get "playerid" by using string methods (see the code below).
Below is the code in Java:
ArrayList<String> player_ids = new ArrayList<String>();
String s = "YOUR STRING";
JSONArray ja = new JSONArray(s);
for(int i =0; i<ja.length(); i++)
{
String value = ja.getJSONObject(i).getString("value");
int start = value.indexOf("=");
int end = value.indexOf(",");
String player_id = value.substring(start+1, end);
player_ids.add(player_id);
}
Hope it helps!!

Categories

Resources