I am new to Javascript and I would like to use the document.getElementById to show the value of items, in my example I would like to list the names printed in the var= btsFrontEnd ,but I am doing something wrong. Any help will be much appreciated.
Thank you.
Link to my Fiddle
var btsFrontEnd = {
"employee-1": {
"name": "Name One",
"phone": "1234567890",
"email": "blah#blah.com"
},
"employee-2": {
"name": "Name Two",
"phone": "1234567890",
"email": "blah#blah."
}
};
var btsemployees = {
employees:[
{
"name": "Name One",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Two",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Three",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Four",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Five",
"phone": "1234567890",
"email": "blah#blah.com"
}
]
};
//First argument is our data structure (an object or an array
//Second argument is a callback (logic we apply to our data structure)
$.each(btsFrontEnd, function (key, value) {
console.log(key); //Prints this object's keys
console.log(value); //Prints immediate values from this object
console.log(btsFrontEnd[key]);
console.log(value.name);
document.getElementById("names").innerHTML.value;// This is what I am referring to, I would like it to appear in the p id="names"
});
Here is the jsfiddle: http://jsfiddle.net/Ss2kk/7/
// Put names into an array
var employeeNames = [];
$.each(btsFrontEnd, function (employeeid, employee) { //first is the key or index, second argument is the value
// Check each element if it has name field
if (employee.name !== undefined) {
// Put its name into the array
employeeNames.push(employee.name);
}
});
// Join the array as comma seperated and put the content into `<p>` tag.
document.getElementById("names").innerHTML = employeeNames.join(",");
Inside your loop the key and value params represent the following values in the first iteration:
key
"employee-1"
value
Object { name="Name One", phone="1234567890", email="blah#blah.com"}
Since value is an object you can acces the name like this: value.name.
var names = document.getElementById( 'names' );
names.innerHTML = '';
$.each( btsFrontEnd, function( key, value ) {
names.innerHTML += value.name + '<br>';
});
All answers listed use jQuery, so I thought it'd be useful to add a pure javascript version. Two versions actually.
The first version uses Object.keys, which is relatively new compared to hasOwnProperty, which is used in the second version. This means the second version is compatible with more browsers.
Version 1:
// Declare variables
var keys, i, names = [];
// Get all keys in the btsFrontEnd object in an array. This is employee-1 and employee-2 in the example.
keys = Object.keys(btsFrontEnd);
// Loop over all keys
for(i = 0; i < keys.length; ++i) {
// Get the name of the employee via it's key and add it to the name array.
names.push(btsFrontEnd(keys[i]).name);
}
//Make one long string from the names with a comma as seperator, then put the string in the dom element.
document.getElementById("names").innerHTML = names.join(",");
Version 2:
// Declare variables
var key, names = [];
//Loop over all object properties
for(key in btsFrontEnd) {
// Check if the property is defined by you, and is not a standard Object property.
if(btsFrontEnd.hasOwnProperty(key)) {
names.push(btsFrontEnd[key].name);
}
}
//Make one long string from the names with a comma as seperator, then put the string in the dom element.
document.getElementById("names").innerHTML = names.join(",");
Related
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.
How can I replace the spaces in a JSON object's keys dynamically? For example, if I have the following object:
[{
"FIRST NAME": "Philip",
"LAST NAME": "Rivers",
"NUMBER": "17",
"GPA": "1.0",
"OLD_FACTOR": "8",
"NICENESS": "1"
}, {
"FIRST NAME": "Peyton",
"LAST NAME": "Manning",
"NUMBER": "18",
"GPA": "4.0",
"OLD_FACTOR": "5000",
"NICENESS": "5000"
}]
I want to be able to dynamically rename "FIRST NAME" and "LAST NAME" to "FIRST_NAME" and "LAST_NAME" respectively. Based on research so far, I have this function:
function replaceSpaces(data) {
debugger;
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
var replacedKey = key.split(' ').join('_');
data[i][obj] = replacedKey;
}
}
return data;
}
The "data" parameter being passed in is an object that has already had JSON.parse ran on it prior to entering this function.
My issue with this code is that it's looping through the keys just fine, and assigning the proper replaced string to "replacedKey", but it's not assigning that to the original data object.
Here's complete code using forEach.
The steps are same as Quentin has stated in his answer
Copy the value
Remove the key-value from the object
Add new item with new value in the object
var arr = [{
"FIRST NAME": "Philip",
"LAST NAME": "Rivers",
"NUMBER": "17",
"GPA": "1.0",
"OLD_FACTOR": "8",
"NICENESS": "1"
}, {
"FIRST NAME": "Peyton",
"LAST NAME": "Manning",
"NUMBER": "18",
"GPA": "4.0",
"OLD_FACTOR": "5000",
"NICENESS": "5000"
}];
// Iterate over array
arr.forEach(function(e, i) {
// Iterate over the keys of object
Object.keys(e).forEach(function(key) {
// Copy the value
var val = e[key],
newKey = key.replace(/\s+/g, '_');
// Remove key-value from object
delete arr[i][key];
// Add value with new key
arr[i][newKey] = val;
});
});
console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>
Strictly if the JSON is get in the form of String from server:
Replace the spaces by _ from the keys.
JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) {
return m.replace(/\s+/g, '_');
}));
You need to:
Copy the value
Delete the old property
Modify the correct object. (data[i][obj] will convert obj to a string and try to use it as a property name).
Such:
for (var original_property in obj) {
var new_property = original_property.split(' ').join('_');
obj[new_property] = obj[original_property];
delete obj[original_property]
}
since it is JSON it is expected to come as string you could do it with a help of Regex.
var processedJson = yourJson.replace(/( +)(?=[(\w* *]*":)/g, "_");
var yourObj = JSON.parse(processedJson);
/( +)(?=[(\w* *]*":)/g will find all ocurances of within " ... ": which is a key on every JSON object.
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");
}
});
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
I have a working version of a function to loop through a single array in a JSON object, e.g.
[{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}]
sample function:
function FindName(NameToFind, data1) {
objData = JSON.parse(data1);
for (var i = 0; i < objData.length; i++) {
var Name = objData[i].Name;
if (Name == NameToFind) {
alert("found!");
}
}
}
Now I need to change this function to allow for either single OR multiple arrays e.g.
{
"Table1": [{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}],
"Table2": [{
"Name": "Sarah",
"Surname": "Parker"
},
{
"Name": "Jonah",
"Surname": "Hill"
}
]
}
Is there a way to determine whether the object has 1 array (like in first example) or more than one arrays (like in 2nd example), and any advice/guidance on how to extend the function to be able to loop through all the items whether it has 1 array or multiple arrays?
Your first object is an array, the second one isn't.
You can test if your argument is an array, or even just test
if (objData[0]) // that's an array
EDIT :
if you want to iterate over all properties of a (just json decoded) object, when it's not an array, you can do this :
for (var key in objData) {
var value = objData[key];
// now use the key and the value
// for example key = "Table1"
// and value = [{"Name":"John","Surname":"Johnson"}, ... ]
}