Chrome Console returning 8 Nan from variable - javascript

I am using the following function
function QuantityCheckout () {
var obj = {
"BackGlassQty": Cookies.get('BackGlassQty'),
"BackCameraQty": Cookies.get('BackCameraQty'),
"BatteryQty": Cookies.get('BatteryQty'),
"ChargingPortQty": Cookies.get('ChargingPortQty'),
"FrontCameraQty": Cookies.get('FrontCameraQty'),
"GlassCameraCoverQty": Cookies.get('GlassCameraCoverQty'),
"LogicBoardQty": Cookies.get('LogicBoardQty'),
"ScreenQty": Cookies.get('ScreenQty')
};
$.each(obj, function (key, value) {
var test = '#' + key - 'qty' + 'Quantity'
console.log(test);
$('#' + key - 'qty' + 'Quantity').text('Quantity:' + value);
});
}
and it keeps returning 8 in a circle and NaNQuantity.

There is no - operator for String in Js. Instead you should use the replace function, and so your code should become:
var test = '#' + key.replace('Qty', '') + 'Quantity'

It's because when you join the string you have a minus in there so it is trying to do a mathematical calculation instead, which is why you get NaN.
Use a + to concatenate the strings.
const Cookies = {
get: () => {}
}
function QuantityCheckout () {
var obj = {
"BackGlassQty": Cookies.get('BackGlassQty'),
"BackCameraQty": Cookies.get('BackCameraQty'),
"BatteryQty": Cookies.get('BatteryQty'),
"ChargingPortQty": Cookies.get('ChargingPortQty'),
"FrontCameraQty": Cookies.get('FrontCameraQty'),
"GlassCameraCoverQty": Cookies.get('GlassCameraCoverQty'),
"LogicBoardQty": Cookies.get('LogicBoardQty'),
"ScreenQty": Cookies.get('ScreenQty')
};
$.each(obj, function (key, value) {
var test = '#' + key + 'qty' + 'Quantity'
console.log(test);
$('#' + key + 'qty' + 'Quantity').text('Quantity:' + value);
});
}
QuantityCheckout()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Alternatively you can use back ticks
var test = `#${key}qtyQuantity`

Related

Reading JSON object value with key pattern

My JSON structure is as follows
var data = [
{name:'bracket', start_45641654:'46513489431',end_26441:'75434'},
{ name: 'notation', end_746413: '2146464', start_51345641: '76542464' },
];
I want to print start, end object values, Here a random number is appending to keys start_ and end_. Tried to use ^ regular expression pattern but it is not working. Is there any other way to print the values?
data.forEach(function (v, i) {
$('tr').prepend('<td>Name:' + v['name'] + '</td>' +
'<td>Start:' + v['^start_'] + '</td>' +
'<td>End:' + v['^end_'] + '</td>'
);
});
You can't use regular expressions there.
You can loop through the properties of the object, checking if the name has the desired prefix.
data.forEach(function(v) {
let start, end;
Object.entries(v).forEach(([key, val]) => {
if (key.startsWith('start_')) {
start = val;
} else if (key.startsWith('end_')) {
end = val;
}
});
$('tr').prepend('<td>Name:' + v.name + '</td>' +
'<td>Start:' + start + '</td>' +
'<td>End:' + end + '</td>'
);
});
var data = [
{name:'bracket', start_45641654:'46513489431',end_26441:'75434'},
{ name: 'notation', end_746413: '2146464', start_51345641: '76542464' },
];
data.forEach(function (v, i) {
var start = Object.keys(v).find((name) => /start/.test(name));
var end = Object.keys(v).find((name) => /end/.test(name));
console.log(start+" "+end);
$('tr').prepend('<td>Name:' + v['name'] + '</td>' +
'<td>Start:' + v[start] + '</td>' +
'<td>End:' + v[end] + '</td>'
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>
Check this. I don't know if accessing object keys using regex and indexing works. But this should work for you.
Note: I write it on the fly you may need to tweak it
for(let item of data) { // iterate through array
for(let key in item) { // iterate through object keys
if(!key.hasOwnProperty()) // you may wont need it, it makes sure the key you are bringing aren't inherited and the current object is owner of them, mostly used with arrays
return
if(key.indexof('start_') >= 0) // which should be 0 if is ok and -1 if not ok
{
// your code for start
// to get value: item[key]
}
if(key.indexof('end_') >= 0) // which should be 0 if is ok and -1 if not ok
{
// your code for end
// to get value: item[key]
}
}
}
Note: that you may read your JSON file/resource as string, not an object (depend on method used), in that case use JSON.parse(<yourStringJson>)
You can achieve this using reduce function of array. You don't need to use for, for each loop and condition related logic.
For example:
const data = [
{ name: "bracket", start_45641654: "46513489431", end_26441: "75434" },
{ name: "notation", end_746413: "2146464", start_51345641: "76542464" },
];
console.log(data);
const startEndData = data.reduce((p, c) => {
const { name, ...rest } = c;
return [...p, rest];
}, []);
console.log(startEndData);

Translate a html attribute to javascript object

$("div").click(function () {
var obj = { flammable: 'inflammable', duh: 'no duh' };
$.each(obj, function (key, value) {
alert(key + ": " + value);
});
});
This works without problem and alerts key/value.
$("div").click(function () {
var obj = $(this).attr("obj");
$.each(obj, function (key, value) {
alert(key + ": " + value);
});
});
<div obj="{ flammable: 'inflammable', duh: 'no duh' }">click</div>
However this is not working?
change this line
var obj = $(this).attr("obj");
to
var obj = JSON.parse($(this).attr("obj"));
Also, you may want to use escaped double quotes rather than single quotes inside the object, make it
<div obj="{ \"flammable\": \"inflammable\", \"duh\": \"no duh\" }">click</div>
or
<div obj= '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}' >click</div>

How do I convert the object passed in to an array of strings

function objectToArray (object) {
var array = [];
var str = "";
for (var key in object) {
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
}
console.log(array);
}
objectToArray({name: "Marcia", age: 101});
The output is [ 'name', 'Marcia', 'age', 101 ] and I need it to be ["name is Marcia", "age is 101"].
Instead of this:
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
You want this:
if (object.hasOwnProperty(key)) {
array.push( key + " is " + object[key] + "" );
}
#VoteyDisciple has correctly pointed out where you went wrong with your approach. An alternate (shorter) way to implement your function is:
function objectToArray (object) {
return Object.keys(object).map(function (key) {
return key + " is " + object[key];
});
}
var arr = objectToArray({name: "Marcia", age: 101});
console.log(arr);

search with an array associate with javascript?

I want to do a search by name and surname with an array javascript, and the results in a div. for example: I write Ali in input, an it shoul show me Alison and Alibaba.
this is my code, but it's giving errors; are there other ways to do it?:
<input type='text' id='filter' placeholder='search'>
<div id='output' style='margin-top:50px '></div>
my array
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#output');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
console.log( item[0].toLowerCase().indexOf(val));
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item[0] + ' ' + item[1] + '</li>');
}
});
$result.html( $fragment.children() );
});
http://jsfiddle.net/henrykend/ChpgZ/4/
The main problem with your code is that you're trying to reference fields in the object by ordinal position rather than name. There is nothing automagic in JavaScript which will read item.Name (or item["Name"]) from item[0].
There is also no need to build up a "false element" (in your case $fragment) and then append its children to the output area - you may as well do this in one go (remembering to .empty() it between calls).
Your corrected code:
var $result = $('#result');
$('#output').on('keyup', function () {
$result.empty();
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$result.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
});
And a live example: http://jsfiddle.net/ChpgZ/6/
You had couple of problems in your code.
Names of the elements we're wrongly placed (which you've fixed with the edit)
In the .each, you've used item[0] instead of item.Name (also surname)
See the following code
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#result');
$('#output').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {console.log( item.Name.toLowerCase().indexOf(val) );
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
$result.html( $fragment.children() );
});

Loop through jquery data() object to get keys and values

I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});​
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye

Categories