I have list of jobs that needs to be perform based on the data and device.
This is my sample data
device = [ device0, device1, device2 ]
device0 = {
group: [MATCH1, MATCH2]
}
device1 = {
group: [MATCH1, MATCH2, MATCH3]
}
device2 = {
group: [MATCH2, MATCH3]
}
data = {
"destination": "destination",
"text": "Test send message",
"hlr": "MATCH2"
}
How can i fix my code so that my data can match and perform task to device. I'm sorry this is my first question. I'm still learning programming and I'm not fluent in english.
This is my sample code :
const jobs = []
jobs.push(data)
if (jobs.length > 0) {
let task= jobs.shift()
device.push(device.splice(0, 1)[0]); // swap device position
dataLoop: for (var i = 0; i < device.length; i++) {
itemLoop: for (var j = 0; j < device[0].group.length; j++) { // cycle through until find match
if (device[0].group[j].toString() === data.hlr.toString()) {
console.log(device[0].group[j] + ':' + data.hlr.toString()); // output should be MATCH2 : MATCH2
break dataLoop;
}
}
device.push(device.splice(0, 1)[0]);
}
device[0].sendData({ // using first device to perform task
receiver: data.destination,
text: data.text,
request_status: true
}, function(err, ref) {
setTimeout(function() {
if (err) { console.log(err) }
console.log(ref)
}, 5000)
});
}
Theres a typo:
itemLoop: for (var j = 0; j < device[i].group.length; j++) {
must be
itemLoop: for (var j = 0; j < device[0].group.length; j++) { //
I have an array like this:
"links": [{
"url": "http:...",
"title": "3"
}, {
"url": "http://facebook.com/pages/",
"title": "2"
},{
"url": "http://...",
"title": "2"
}],
I want to find out of the array has the word 'facebook' and if so to take the specific url with the word and use it. I tried this code but it doesn't work.
var arraylinks = mdata.links;
if (arraylinks[i].url === "facebook") {
for (var i = 0; i < arraylinks.length; i++) {
var klink = $("<a>").attr("href", arraylinks[i].url).attr('target', '_blank').addClass("icon-library");
}
}
I would appreciate your help. thank you
You can use Array.filter, Regex to filter your list.
var array = [{
"url": "http:...",
"title": "3"
}, {
"url": "http://facebook.com/pages/",
"title": "2"
},{
"url": "http://...",
"title": "2"
}];
var filtered = array.filter(function (obj) {
return /facebook/i.test(obj.url);
})
console.log(filtered[0]);
You could use indexOf on the urls to keep it basic.
var arraylinks = mdata.links;
var wordToFind = "facebook"
if (arraylinks[i].url && arraylinks[i].url.toLowerCase().indexOf(wordToFind) >= 0 ) {
for (var i = 0; i < arraylinks.length; i++) {
var klink = $("<a>").attr("href", arraylinks[i].url)
.attr('target', '_blank').addClass("icon-library");
}
}
so you could do this:
var arraylinks = mdata.links;
for (var i = 0; i < arraylinks.length; i++) {
if (arraylinks[i].url.indexOf("facebook") != -1) {
var klink = $("<a>").attr("href", arraylinks[i].url).attr('target', '_blank').addClass("icon-library");
// do something with klink here
}
}
I also think the for loop needs to be outside of the if statement
You can use this
fbLink = links.find(function(el){
return el.url.indexOf('facebook') >= 0
});
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++) {
...
}
I have a generated JSON file that I would like to transform. Is there an easy way to transform the "id"/"value" form of this JSON to a proper key/value JSON object, without using any frameworks?
These lines:
"value":"chrome",
"id":"foo"
would convert to:
"foo": "chrome"
Input JSON:
{"row":[
{
"column":[
{
"value":"chrome",
"id":"foo"
},
{
"value":0,
"id":"bar"
},
{
"value":"baz1",
"id":"baz"
},
{
"value":0,
"id":"legacy"
}
]
},
{
"column":[
{
"value":"firefox",
"id":"foo"
},
{
"value":0,
"id":"bar"
},
{
"value":"baz2",
"id":"baz"
},
{
"value":0,
"id":"legacy"
}
]
}
]
}
Desired JSON:
{"row":[
{
"foo":"chrome",
"bar":0,
"baz":"baz1",
"legacy":0
},
{
"foo":"firefox",
"bar":0,
"baz":"baz2",
"legacy":0
}
]
}
Here is the solution:
var result = {"row": []}
for (var i = 0; i < input["row"].length; i++) {
var object = {};
var column = input["row"][i]["column"];
for (var j = 0; j < column.length; j++) {
object[column[j]["id"]] = column[j]["value"];
}
result.row.push(object);
}
console.log(result);
input variable refers to your initial JSON object.
var input = {"row":[
{
"column":[
...
here is my function, i was typing it out allready before ioseb posted his answer so i figured it post it as well, it's linted and everything
function transform(data) {
"use strict";
var x, i, row, column, colNumb, out = {rows : []}, rownum = data.row.length;
for (x = 0; x < rownum; x += 1) {
row = {};
column = data.row[x].column;
colNumb = column.length;
for (i = 0; i < colNumb; i += 1) {
row[column[i].id] = column[i].value;
}
out.rows.push(row);
}
return out;
}
How can i update the following JSON object dynamically using javascript or Jquery?
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
I would like to dynamically update the Username to 'Thomas' where the 'Id' is '3'.
How can I achieve this?
A plain JavaScript solution, assuming jsonObj already contains JSON:
Loop over it looking for the matching Id, set the corresponding Username, and break from the loop after the matched item has been modified:
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === 3) {
jsonObj[i].Username = "Thomas";
break;
}
}
Here it is on jsFiddle.
Here's the same thing wrapped in a function:
function setUsername(id, newUsername) {
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === id) {
jsonObj[i].Username = newUsername;
return;
}
}
}
// Call as
setUsername(3, "Thomas");
simply iterate over the list then check the properties of each object.
for (var i = 0; i < jsonObj.length; ++i) {
if (jsonObj[i]['Id'] === '3') {
jsonObj[i]['Username'] = 'Thomas';
}
}
$(document).ready(function(){
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}];
$.each(jsonObj,function(i,v){
if (v.Id == 3) {
v.Username = "Thomas";
return false;
}
});
alert("New Username: " + jsonObj[2].Username);
});
use:
var parsedobj = jQuery.parseJSON( jsonObj);
This will only be useful if you don't need the format to stay in string.
otherwise you'd have to convert this back to JSON using the JSON library.
var i = jsonObj.length;
while ( i --> 0 ) {
if ( jsonObj[i].Id === 3 ) {
jsonObj[ i ].Username = 'Thomas';
break;
}
}
Or, if the array is always ordered by the IDs:
jsonObj[ 2 ].Username = 'Thomas';
JSON is the JavaScript Object Notation. There is no such thing as a JSON object. JSON is just a way of representing a JavaScript object in text.
So what you're after is a way of updating a in in-memory JavaScript object. qiao's answer shows how to do that simply enough.
I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.
function setVal(update) {
/* Included to show an option if you care to use jQuery
var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
targetField: null, targetData: null, checkAllRows: false };
//update = $.extend({}, defaults, update); */
for (var i = 0; i < update.jsonRS.length; i++) {
if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
update.jsonRS[i][update.targetField] = update.targetData;
if (!update.checkAllRows) { return; }
}
}
}
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
With your data you would use like:
var update = {
jsonRS: jsonObj,
lookupField: "Id",
lookupKey: 2,
targetField: "Username",
targetData: "Thomas",
checkAllRows: false
};
setVal(update);
And Bob's your Uncle. :) [Works great]
For example I am using this technique in Basket functionality.
Let us add new Item to Basket.
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image'), "quantity":1, "discount":0, "total":$(this).attr('pr_price')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
itemCountInCart(productArray.length);
});
After adding some item to basket - generates json array like this
[
{
"id": "95",
"nameEn": "New Braslet",
"price": "8776",
"image": "1462012394815.jpeg",
"quantity": 1,
"discount": 0,
"total": "8776"
},
{
"id": "96",
"nameEn": "new braslet",
"price": "76",
"image": "1462012431497.jpeg",
"quantity": 1,
"discount": 0,
"total": "76"
},
{
"id": "97",
"nameEn": "khjk",
"price": "87",
"image": "1462012483421.jpeg",
"quantity": 1,
"discount": 0,
"total": "87"
}
]
For Removing some item from Basket.
$(document).on('click','[itemRemoveBtn]',function(){
var arrayFromLocal=localStorage.getObj('product');
findAndRemove(arrayFromLocal,"id",$(this).attr('basketproductid'));
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});
//This function will remove element by specified property. In my case this is ID.
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
console.log('Removed from index is '+index+' result is '+JSON.stringify(result));
array.splice(index, 1);
}
});
}
And Finally the real answer of the question "Updating a JSON object using JS". In my example updating product quantity and total price on changing the "number" element value.
$(document).on('keyup mouseup','input[type=number]',function(){
var arrayFromLocal=localStorage.getObj('product');
setQuantityAndTotalPrice(arrayFromLocal,$(this).attr('updateItemid'),$(this).val());
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});
function setQuantityAndTotalPrice(array,id,quantity) {
array.forEach(function(result, index) {
if(result.id === id) {
result.quantity=quantity;
result.total=(quantity*result.price);
}
});
}
I think this the more efficent way than for looping.
1-First find index of item.
2-Second edit exact element. (if not exist add)
Example :
let index= jsonObj.findIndex(x => x["Id"] === 3);
if (index == -1) {
// add
jsonObj.push({ id:3, .... });
} else {
// update
jsonObj[index]["Username"]="xoxo_gossip_girl"
}
var jsonObj = [{'Id':'1','Quantity':'2','Done':'0','state':'todo',
'product_id':[315,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
'Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Quantity':'2','Done':'0','state':'todo',
'product_id':[314,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
'Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Quantity':'2','Done':'0','state':'todo',
'product_id':[316,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
'Username':'Albert','FatherName':'Einstein'}];
for (var i = 0; i < jsonObj.length; ++i) {
if (jsonObj[i]['product_id'][0] === 314) {
this.onemorecartonsamenumber();
jsonObj[i]['Done'] = ""+this.quantity_done+"";
if(jsonObj[i]['Quantity'] === jsonObj[i]['Done']){
console.log('both are equal');
jsonObj[i]['state'] = 'packed';
}else{
console.log('not equal');
jsonObj[i]['state'] = 'todo';
}
console.log('quantiy',jsonObj[i]['Quantity']);
console.log('done',jsonObj[i]['Done']);
}
}
console.log('final',jsonObj);
}
quantity_done: any = 0;
onemorecartonsamenumber() {
this.quantity_done += 1;
console.log(this.quantity_done + 1);
}
//update & push json value into json object
var sales1 = [];
if (jsonObj && Object.keys(jsonObj ).length != 0) {
jsonObj .map((value) => {
const check = sales1.filter(x => x.order_date === String(value.order_date).substring(0, 10))
if (check.length) {
sales1.filter(x => x.sale_price = Number(x.sale_price) + Number(value.sale_price))
} else {
let data = { "sale_price": Number(value.sale_price), "order_date": String(value.order_date).substring(0, 10) }
sales1.push(data)
}
})
}
You can easily update the username dynamically to 'Thomas' where the 'Id' is '3' using the following.
jsonObj.find(i=>i.Id===3).Username='Thomas'