Unable to display array content - javascript

var dataHolder = [
{
"letterA" : "Fruits",
"letterB" : "Veges",
"letterC" : "Meat"
}
];
console.log(dataHolder[0].letterA);
var result = "";
function getData(myLetter) {
for (var i = 0; i < dataHolder.length; i++) {
if(dataHolder[i][myLetter] === myLetter){
console.log(dataHolder[i][myLetter]);
}
else{
console.log("No data found");
}
}
}
getData("letterA");
This is my code and i'm just trying to match the content of the array with the passed parameter, but every time it's giving No data found as output and not the matching content, it seems i'm missing something very basic here.
Any help would be highly appreciated.Thanks!!

You matching was wrong.
you are matching the letters == fruites .You should check is the key exist or not ,that's enough using hasOwnProperty()
Check this below. i was mention the error
var dataHolder = [{
"letterA": "Fruits",
"letterB": "Veges",
"letterC": "Meat"
}];
var result = "";
function getData(myLetter) {
for (var i = 0; i < dataHolder.length; i++) {
console.log('this is the pblm '+dataHolder[i][myLetter] +' != '+myLetter)
if (dataHolder[i].hasOwnProperty(myLetter)) {
console.log(dataHolder[i][myLetter]);
} else {
console.log("No data found");
}
}
}
getData("letterA");
For your way use with for...in
var dataHolder = [{
"letterA": "Fruits",
"letterB": "Veges",
"letterC": "Meat"
}];
var result = "";
function getData(myLetter) {
for (var i in dataHolder) {
if (dataHolder[i].hasOwnProperty(myLetter)) {
console.log(dataHolder[i][myLetter]);
} else {
console.log("No data found");
}
}
}
getData("letterA")

You are comparing value with key that is wrong.
The hasOwnProperty() method returns a boolean indicating whether the
object has the specified property as own (not inherited) property.
Use hasOwnProperty to check key exists or not.
dataHolder[i].hasOwnProperty(myLetter)
var dataHolder = [
{
"letterA" : "Fruits",
"letterB" : "Veges",
"letterC" : "Meat"
}
];
var result = "";
function getData(myLetter) {
for (var i = 0; i < dataHolder.length; i++) {
if(dataHolder[i].hasOwnProperty(myLetter)){
console.log(dataHolder[i][myLetter]);
}
else{
console.log("No data found");
}
}
}
getData("letterA");

Related

Check if the property exist in array

The name attribute_name:"position" is very rare and I want to check that if the property exists I want to push it to the new array. However, every time I try to add a condition it gives me errors.
[0].attribute_name inside the for loop is giving me trouble. There may or may not be two arrays inside activity_attributes. But I want to make a call bases on first array, if the itemloop[i].activity_attributes[0].attribute_name push them to new array.
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i<itemloop.length; i++){
if(itemloop[i].activity_attributes[0].attribute_name == "position") {
social_post_link.push(itemloop[i].activity_attributes);
}
}
console.log(social_post_link);
}
You can use if('attribute_name' in yourObject) to achieve that.
Demo.
var res = {
status: 'success',
response: {
activities : [
{
activity_attributes: [
{
attribute_name: 'position'
}
]
},
{
activity_attributes: [
{
test: 'test'
}
]
}
]
}
};
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i<itemloop.length; i++){
if( 'attribute_name' in itemloop[i].activity_attributes[0]){ //HERE
if(itemloop[i].activity_attributes[0].attribute_name == "position") {
social_post_link.push(itemloop[i].activity_attributes);
}
}
}
console.log(social_post_link);
}
Use should use the hasOwnProperty method
if(itemloop[i].activity_attributes[0].hasOwnProperty('attribute_name') && itemloop[i].activity_attributes[0].attribute_name == "position")
You code should be like
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i<itemloop.length; i++){
if(itemloop[i].activity_attributes[0].hasOwnProperty('attribute_name') && itemloop[i].activity_attributes[0].attribute_name == "position") {
social_post_link.push(itemloop[i].activity_attributes);
}
}
console.log(social_post_link);
}
Array.prototype.filter() and Array.prototype.map() can be combined to construct new arrays based on predicated rules such as attribute_name == 'position' and return child values.
See below for a practical example.
if (res.status == 'success') {
const itemloop = res.response.activities
const social_post_link = itemloop.filter(x => x.attribute_name == 'position').map(x => x.activity_attributes)
console.log(social_post_link)
}
instead of activity_attributes[0].attribute_name ,try using activity_attributes[0]['attribute_name'] == 'position'

JSON array filter does not apply

I am trying to filter the data from an array, but it is throwing an error saying
filter() is not function
Here is the code:
var selectedObject = [];
selectedObject= JSON.stringify(formsDataSource.data());
//console.log(selectedObject);
//var filtered = $.grep(selectedObject, function (el) {
// return el.po_order_no = 18;
//});
//console.log((filtered));
if (selectedObject == undefined) {
alert("Undefined");
} else {
var data= selectedObject.filter(function (element) { return element.po_order_no = "18"; })
alert("" + data);
}
I tried many things but it is still throwing an error. Any help?
Few observations :
selectedObject= JSON.stringify(formsDataSource.data());
This statement states that selectedObject is a string. A string does not have a filter() method.
condition inside filter function should be element.po_order_no == "18" instead of element.po_order_no = "18"
Solution :
var selectedObject = [
{
"po_order_no": 18,
"po_order_name": "abc"
},
{
"po_order_no": 19,
"po_order_name": "xyz"
}
];
if (selectedObject == undefined) {
console.log("Undefined");
} else {
var data = selectedObject.filter(element => element.po_order_no == "18")
console.log(data);
}

Accurate value from the JSON Array

Trying to match the value with the JSON value by wrirting a for loop, but everytime once the loop is completes it is returning 2345 value only. Where am I going wrong can anyone help me out.
And I have a term which dynamically generates a string value.
var mKey = doc.search.searchBy.split(",")[0].split("=")[1].replace(/\s+/, "").toLowerCase();
JSON:
{
"records" : {
"cat1" : [
{
"id" : 1234,
"label":"a"
},
{
"id" : 2345,
"label":"b"
}
],
"cat2" : {
"id" : 12345,
"label" : "c"
}
}
}
JS:
var array = doc.records.cat1;
for (var i=0; i<array.length; i++) {
var oID = array[i].id.toString();
}
if (oID === "2345" && mKey=="Apple") {
console.log("Apple");
break;
}
else if (oID === "1234" && mKey=="Banana") {
console.log("Banana")
}
else {
console.log('other fruits');
}
You need to place your if statement within the for loop so that it relates to the current iteration:
var array = doc.records.cat1;
for (var i = 0; i < array.length; i++) {
var oID = array[i].id.toString();
if (oID === "2345") {
console.log("success");
}
else if (oID === "1234") {
console.log("error")
}
else {
console.log('other');
}
}
Example fiddle
Note that a break statement is irrelevant inside an if block.
You have closed your loop in wrong place, I guess
for (var i=0; i<array.length; i++) {
var oID = array[i].id.toString();
if (oID === "2345") {
console.log("success");
break;
}
else if (oID === "1234") {
console.log("error")
}
else {
console.log('other');
}
}
All if structure comes under for loop
var array = doc.records.cat1;
for (var i=0; i<array.length; i++) {
var oID = array[i].id.toString();
if (oID === "2345" && mKey=="Apple") {
console.log("Apple");
break;
}
else if (oID === "1234" && mKey=="Banana") {
console.log("Banana")
}
else {
console.log('other fruits');
}
}

Getting nested obj value

Given the following obj:
var inputMapping = {
nonNestedItem: "someItem here",
sections: {
general: "Some general section information"
}
};
I'm writing a function to get that data by passing in a string "nonNestedItem" or in the nested case "sections.general". I'm having to use an eval and I was wondering if there was maybe a better way to do this.
Here is what I have so far and it works okay. But improve!
function getNode(name) {
var n = name.split(".");
if (n.length === 1) {
n = name[0];
} else {
var isValid = true,
evalStr = 'inputMapping';
for (var i=0;i<n.length;i++) {
evalStr += '["'+ n[i] +'"]';
if (eval(evalStr) === undefined) {
isValid = false;
break;
}
}
if (isValid) {
// Do something like return the value
}
}
}
Linky to Jsbin
You can use Array.prototype.reduce function like this
var accessString = "sections.general";
console.log(accessString.split(".").reduce(function(previous, current) {
return previous[current];
}, inputMapping));
Output
Some general section information
If your environment doesn't support reduce, you can use this recursive version
function getNestedItem(currentObject, listOfKeys) {
if (listOfKeys.length === 0 || !currentObject) {
return currentObject;
}
return getNestedItem(currentObject[listOfKeys[0]], listOfKeys.slice(1));
}
console.log(getNestedItem(inputMapping, "sections.general".split(".")));
You don't need to use eval() here. You can just use [] to get values from an object. Use a temp object to hold the current value, then update it each time you need the next key.
function getNode(mapping, name) {
var n = name.split(".");
if (n.length === 1) {
return mapping[name];
} else {
var tmp = mapping;
for (var i = 0; i < n.length; i++) {
tmp = tmp[n[i]];
}
return tmp;
}
}

Jquery json : Uncaught TypeError: Cannot read property 'xx' of undefined

I am retrieving data via JSON but the problem is that I am getting error as such "Cannot read property 'productid' of undefined".
JSON File (data.json)
{
"Products": [
{
"productid": "135",
"productname": "Shirt",
"productqty": "3",
"seller_3": "150.00",
"seller_2": "151.00",
"seller_7": "153.00",
"seller_6": "159.00",
"seller_5": "155.00",
"seller_1": "157.00",
"seller_4": "152.00"
}
]
}
The execution code is
var itemQty = 134;
$.getJSON( "../data.json", function(data) {
if (data.Products.length == 0) {
/*do nothing*/
} else if(data.Products.length > 0){
for (var i = 0; i < data.Products.length; i++) {
console.log(data.Products[i].productid); // ITS RETURN THE VALUE 135
if (data.Products[i].productid == itemID) { // <--- ERROR THIS LINE
if (data.Products[i].productqty == itemQty) {
newQuantity = eval(data.Products[i].productqty);
} else {
var newQuantity = eval(itemQty);
}
if (newQuantity > options.quantityLimit) {
newQuantity = options.quantityLimit
}
data.Products[i].productqty = newQuantity;
} else {
data.Products.push(cartItem);
}
}
}
}
In the console.log, it returns the value which is 135, where as when comparing in the IF statement, I am getting the error Cannot read property 'productid' of undefined.
It looks like you are modifying the list of Products from inside the loop. So take a closer look at whatever is setting the value for cartItem.
for (var i = 0; i < data.Products.length; i++) {
...
data.Products.push(cartItem);
}
It is a bad idea to add new items to a list while you're iterating over it. You are likely to have an infinite loop depending on how itemID and cartItem are set.
Try reading the .length value one time before starting the loop, so new items won't be iterated:
for (var i = 0, len = data.Products.length; i < len; i++) {
...
}

Categories