So when I retrieve a cookie in javascript I get it like this
"[\"name\"\054 \"name1\"\054 \"name2\"\054 \"name3\"\054 \"name4\"\054 \"name5\"]"
How to change it to be a list as below?
["name", "name1", "name2", "name3", "name4", "name5"]
const parsed = JSON.parse("[\"name\"\054 \"name1\"\054 \"name2\"\054 \"name3\"\054 \"name4\"\054 \"name5\"]");
console.log(parsed); // ["name", "name1", "name2", "name3", "name4", "name5"]
Your cookie was stored as a JSON string, so when you retrieve it you need to use JSON to turn it back into an array (a list). Make sure it isn't null first, though:
if (typeof retrievedCookie == "string") {
var myArray = JSON.parse(retrievedCookie)
} else {
// retrievedCookie is probably null or undefined
var myArray = []
}
Just parse it like this:
JSON.parse(list)
Related
I would like to format my data with a key to access the information. This is what I currently have:
const dict = [];
dict.push({"student": "Brian", "id":"01", "grade":"Sophomore"})
return dict;
Output:
{
"student":"Brian"
"id": "01",
"grade": "Sophomore"
}
However, I am interested in creating this type of format with my data:
{
"student":"Brian" [
{
"id":"01",
"grade": "Sophomore"
}
]
}
How would I be able to do so? I would like to use "student" as my key to access the rest of its information associated.
You're basically there. However objects always need keys to go along with the values, so you need to assign a key to the object you want to create
const dict = [];
dict.push({
"Brian": {
"id": "01",
"grade": "Sophomore"
}
})
// to retrieve:
let brian = dict.filter(e=>Object.keys(e)[0]==="Brian").flatMap(Object.values)
if (brian && brian.length>0) console.log(brian[0])
//You could also set up your `dict` like this:
const dict2 = {};
dict2["Brian"] = {
"id": "01",
"grade": "Sophomore"
};
//and that would allow you to retrieve your object with
brian = dict2.Brian;
console.log(brian)
I would like to be able to type in "Hammerhead" to call the "Hammerhead Shark" object without its full name. Is this possible and if so how?
I tried using array.indexOf(string) though it doesn't really seem to help since it requires an exact match such as typing "Hammerhead Shark"
JS:
const JSON = require('animals.json');
var animals = Object.keys(JSON);
if (animals.indexOf("Hammerhead")) {
console.log(JSON["Hammerhead"].name);
}
JSON:
{
"Hammerhead Shark": {
"name": "Shark",
"age": "300"
},
"Duck": {
"name": "Duck",
"age": "1000"
}
}
I expect the output to be "Shark" instead of undefined.
It seems you want to get access the value in object. By its partial name.
Get the entries of object using Object.entries()
Find the key which includes() the given partial key.
return the second element of the found entry.
const obj = { "Hammerhead Shark": { "name": "Shark", "age": "300" }, "Duck": { "name": "Duck", "age": "1000" } }
function getValueByPartialKey(obj,key){
return (Object.entries(obj).find(([k,v]) => k.includes(key)) || [])[1]
}
console.log(getValueByPartialKey(obj,"Hammerhead"))
You can use string.includes(word) to return the name that matches the string that you're searching for, along with Array.filter iterates over the values too, and returns the result(s) you want.
I want to create a schema in mongoDB for using in an AngularJS project. But the keys for the json are changing dynamically. The json is like this:
{
“1” : {
“Name” : “John”,
“City” : “London”
},
“2” : {
“Name” : “Paul”,
"City” : “New York”
}
}
Here the keys are changing. They will always be in integer format for sure. For the values, I can have my schema like this: (using Javascript)
var dbObject = new Schema({
Name: String,
City: String
});
I am not sure how to include the key which will always be an Integer in this schema. Any pointers for creation of such a schema object in mongoDB?
try this
var data = {
"1": {
"Name": "John",
"City": "London"
},
"2": {
"Name": "John",
"City": "London"
}
};
for (let key in data) {
var val = data[key]; // get inner objects
// call api
}
I am using AngularJS. I have a json object as below;
info = [
{
"name": "Tom",
"id": "111"
},
{
"name": "Sam",
"id": "222"
},
{
"name": "James",
"id": "333"
}
]
I want to have a function such that when a matching name is found, some action is taken (in this -case, return the corresponding id.) In other words, if the input matching name is 'Tom', I want to return the id '111' based on the json object above.
I wrote some code to find a matching name.
$scope.getIdFromName = function()
{
angular.forEach(info, function(value, key)
{
//$scope.searchByName contains the name to be matched
if (key === 'name' && value === $scope.searchByName)
{
//$scope.searchById is the id to be returned
$scope.searchById = key;
alert("found");
}
});
};
Where did the code go wrong? Or is it so wrong that it is better to be completely rewritten? Any suggestions (does not need to be angularjs) will be most welcome. Thank you very much.
Since info is an array of objects, the key is going to be the index of each item, and value will be the whole object at that index. Your forEach should look like this:
angular.forEach(info, function(value, key)
{
//$scope.searchByName contains the name to be matched
if (value.name === $scope.searchByName)
{
//$scope.searchById is the id to be returned
$scope.searchById = value.id;
alert("found");
}
});
Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
Just want to confirm this. If so, how can I use JavaScript to know if the JSON "example" field contains the first homogeneous objects or the second heterogeneous objects?
You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.
you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property
var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
//do something
}
It doesn't matter you can mix and match as much as you want.
You could just test it
typeof someItem.example !== 'undefined' // True if `example` is defined.
It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.
You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.
one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.
as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.
var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];
var parser = {
fruit:function(f){
console.log("fruit:" + f.color);
},
dog: function(d){
console.log("dog:"+d.name);
}};
for(var i=0;i<array.length;i++){
parser[array[i].type](array[i]);
}