How do you index incomplete strings to JSON keys? - javascript

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.

Related

map a 3 nested array javascript

const aboutMe = [{
"name": "frank",
"about": [{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": []
}
]
}]
const AllBreak = aboutMe.about.map((dinner) => ((dinner.first, dinner.last)));
const expectedOutput =["first": "desert", "last": "noodles", "first": "desert", "last": "noodles"]
console.log(aboutMe, AllBreak, expectedOutput)
so am trying to filter through a nested array learning from a tutorial I don't know why it returns cannot read property of map why is that pretty sure i filtered correctly according to the tutorial
Firstly, aboutMe is an array with an object that has an about property in it. So, if you want to access this property, you need to first access the first element of the array and then access the about property in it.
Secondly, (dinner.first, dinner.second) doesn't actually make any sense here.
Because when you have multiple expressions separated by commas in a bracket, each of those expressions get evaluated but only the last one is returned. So, here returning (dinner.first, dinner.second) is equivalent to returning dinner.second.
So, if you only want dinner.second then just return that or put them in an array (or object) and return that.
Also, since in your example it seems that it is not guaranteed that the dinner array would always have an object inside it, it is best to use Optional Chaining here.
Please have look at the solution below:
const
aboutMe = [{name:"frank",about:[{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[]}]}],
res = aboutMe[0].about.map(({dinner}) => [dinner?.[0]?.first, dinner?.[0]?.last])
console.log(res);
aboutMe is an array, if you want to get the property of the first element, you can use indexing [0]
const AllBreak = aboutMe[0].about.map(() => ...);

How to pull a property like "customer.gender" from an array of object with map [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 4 years ago.
I am using javascript map to loop through an array of object. Today i have to loop through an array of object which looks like,
averageReport = [
{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
What i tried to get only the "customer.gender",
averageReport
.map(x => console.log(x.customer.gender)
)
I get the error "Cannot read property 'gender' of undefined"
code on stackblitz
Try,
averageReport
.map(x => console.log(x["customer.gender"])
Since you named your key customer.gender you can't use dot-notation to get the value, you have to use bracket notation ([]).
Also mapping to console.log() doesn't make much sense (since console.log() returns undefined, you are creating a new array of undefined when using map() here), just use forEach():
averageReport = [{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
averageReport.forEach(x => console.log(x["customer.gender"]));
If you want to access the property using dot-notation, you have to make customer an object and gender a property of it, like so:
averageReport = [{
"result": 150.54909908933223,
"customer": {
"gender": "Female"
}
},
{
"result": 150.35230422844595,
"customer": {
"gender": "Male"
}
}
];
Use bracket notation for accessing the customer.gender property. Try the following :
var averageReport = [ { "result": 150.54909908933223, "customer.gender": "Female" }, { "result": 150.35230422844595, "customer.gender": "Male" } ];
var result = averageReport.map(x =>x["customer.gender"]);
console.log(result);

Extracting a corresponding value in json object in AngularJS

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?

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]);
}

Complex JSON string Parsing in JavaScript

This is my sample JSON file , which im trying to parse and read the values ....
C = {{
"Travel": {
"ServiceProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
},
"BusProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
}
}
}
I'm pretty new to JS , and i need to access the nested elements in a generic fashion.
Im not able to extract the details properly. Im getting stuck accessing nested the child elements.
The problem for me is that i wont always know the names of the "key's' to acess them , the JSON will be dynamic , hence i need a generic mechanism to acess the nested child elements. The Nesting can go upto 3 -4 levels.
what notation do we use to access the key / value pairs when the nesting is deep.
Any Help would be appreciated.
ater desirializing your object you can do this
var resultJSON = '{"name":"ricardo","age":"23"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key
alert(k + ' is the key)
}
you can do it using recursively offcourse like this - Link Here
the way is the same just adapt to your example
For dynamic access you can use brackets notation i.e. var json = {nonKnown: 1}; now you can access it like that:
var unknowPropertyName = "nonKnown";
var value = json[unknownPropertyName];
But if you can not even define dynamically name of the property, then you should use
for(variableName in json){
if(json.hasOwnProperty(variableName)){
console.log(variableName);
}
}
You should get the basic idea from this. Good luck

Categories

Resources