JSON Object of Arrays - javascript

I'm pulling my hair now with this. I have this str variable in parent window after getting from child window with JSON.stringify. The group of arrays are a collection of inputs.
var str = {"SHOP1":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\"",
"SHOP2":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\""};
What I did was
for(var i in str) {
console.log(i);
console.log(JSON.parse(str[i]));
}
//the output example:
SHOP1
[["name1",1,"anotherdata1"],["name2",2,"anotherdata2"]]
But it will never detect [["name1",1,"anotherdata1"],["name2",2,"anotherdata2"]] as an array but as string.
Is there any way to make Javascript to detect it as an array? Or is there better suggestion or alternative to this?

The trick is to parse it twice. First to get the string, then second to convert it to the arrays.
var obj = {"SHOP1":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\"",
"SHOP2":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\""};
for (var shopname in obj) {
var shop = obj[shopname];
shop = JSON.parse(JSON.parse(shop));
console.log(shop);
console.log(shop.length);
}

Related

Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C#

I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0

get the value of an object key value that was stringify

I save some items in localstorage and stringify the key value before storing it.
localStorage.setItem(this.set_name, JSON.stringify(this.description))
That gives me key:
item1 Value: [{"description": "some description that was store"}, {"description": "some description that was store"}]
When i get the key value with JSON.parse it returns as an Object Object as expected, So without doing the JSON.parse it will return the whole value as is.
What I want to do is to return what's inside the description only, the "some description that was store" and not the whole value.
How would I do it?
function loadStorage() {
$itemSection = $("#item-section-set");
var keys = Object.keys(localStorage),
i = 0,
key;
for (; key = keys[i]; i++) {
let itemDesc = localStorage.getItem(key);
console.log(JSON.parse(itemDesc))
}
}
Console gives me '(3) [{…}, {…}, {…}]'
You should parse it first, and then fetch it from the array.
Considering that var stringy is the data you got from your localstorage, replace it with localStorage.getItem(<your key>);
var stringy = "[{\"description\": \"some description that was store 1\"}, {\"description\": \"some description that was store 2\"}]"
var parsedArray = JSON.parse(stringy);
for(var i = 0; i < parsedArray.length; i++){
document.getElementById('area').innerHTML += '<p>'+parsedArray[i].description+'</p>';
}
<div id="area"></div>
In general i would create separate service like
storage it should make stringify on save and JSON.parse on get
also it should have inner cache object - parsed object or undefined if object is not in cache and should be extracted and parsed from localStorage
if you are aware about performance, and you can't use JSON.parse due to too large object or similar, i would try to save descriptions in separate key-value pair
like
localStorage.setItem(this.set_name, JSON.stringify(this.description));
localStorage.setItem(this.set_name+'_'+this.descriptionKey,JSON.stringify(this.description))
to have possibility to retrieve description only by descriptionKey without parsing all object
I tried to understand you problem, but m not sure if i did, still assuming, you are saving whole List/Array as an one item in single LocalStorageItem, you will have multiple descriptions in one item, so there are multiple arrays, and each array having multiple objects hence multiple descriptions, heres my solution for this problem, if you explain more i will edit the same.
function loadStorage() {
$itemSection = $("#item-section-set");
var keys = Object.keys(localStorage),
i = 0,
key;
for (; key = keys[i]; i++) {
let itemDesc = localStorage.getItem(key);
var oneLocalStorageItem = JSON.parse(itemDesc);
oneLocalStorageItem.map(function(oneObjectItem){
console.log(oneObjectItem.description);
})
}
}

how to find specific objects and put them in an array in javascript

I have this result in my script
'[{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Montego Bay, Jamaica"},{"region":"NCA","depprt":"Montego Bay, Jamaica"}]'
this is the code to get it.
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.stringify(jsonList);
for jsList I got above result.now I want to get all depprt where region is equal to NCA.how can I do that.
You can use the .filter() method for this.
var ncaList = jsonList.filter(function(obj){ return obj.region == "NCA"; });
Very simple. Iterate over the jList array and see if the region property matches your condition or not then append the item to your filtered array.
var filtered = [];
jList.forEach(function(item) {
if(item.region == 'NCA') {
filtered.push(item);
}
});
Just iterate over it:
var filteredDepprts = [];
jsList.forEach(function(element){
if(element.region == 'NCA'){
filteredList.push(element.depprt); //or element if you want to push the full object
}
});
The JSON.stringify method converts a JavaScript value to a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
When you want to convert a JSON string to a JavaScript value, use JSON.parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.parse(jsonList);
Using single quotes around your #Html.Raw, creates a string and not a JavaScript value. The filter method does not work on strings
Eventually you could use Array.prototype.filter Filter out each element in array, that matches your criteria.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Try map:
var obj= [];
for (i in jsonList) {
if (jsonList[i].region == "NCA") { obj.push(jsonList[i])};
}
https://jsfiddle.net/pd6hvn78/

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

Javascript: Removing an object from array by checking it's attribute

I might have written a pretty confusing title but my question is rather simple.
I'm looking for an efficient way to remove an item from an array. But my array is full objects that has been stringified (I'm writing my app on Node.js and I'm using JSON.stringify method). So my array is like this;
"{\"userID\":\"15\",
\"possibleFollowers\":[
{\"followerID\":\"201\",\"friends\":716},
{\"followerID\":\"202\",\"friends\":11887},
{\"followerID\":\"203\",\"friends\":11887}],
\"name\":\"John\",
\"lon\":\"Doe\"}"
My question is on Javascript(or Node). If I wanted to remove the from possibleFollowers with "followerID: 202", how would I be able to do that efficiently?
var string = "…";
var obj = JSON.parse(string);
obj.possibleFollowers = obj.possibleFollowers.filter(function(fol) {
return fol.followerID != "202";
});
string = JSON.stringify(obj);
var data = "{\"userID\":\"15\",\"possibleFollowers\":[{\"followerID\":\"201\",\"friends\":716},{\"followerID\":\"202\",\"friends\":11887},{\"followerID\":\"203\",\"friends\":11887}],\"name\":\"John\",\"lon\":\"Doe\"}";
var dataObject = JSON.parse(data);
dataObject.possibleFollowers = dataObject.possibleFollowers.filter(function(follower) {
return !(follower.followerID == "202");
});
data = JSON.stringify(dataObject);
In javascript, the splice method is used to delete an array element by index.
see :
http://www.roseindia.net/java/javascript-array/javascript-array-remove-index.shtml
try just to delete it by using "delete"
for (var i in possibleFollowers) {
if (possibleFollowers[i]['followerId'] == '216') {
delete possibleFollowers[i];
}
}

Categories