I am working on a chrome plugin that fetches data. But now i have been running into a problem, I have been asked to put together a nested array with all the data I have retrieved but I have no clue on how to pull this off.
What i want to create:
var messagedata [{
time: messageTime,
Date: messageDate,
Text: messageText
{
time: messageTime,
Date: messageDate,
Text: messageText
}
}];
Note that I know how to create the above when I have the variables. That is not the problem. But in this case i do not know how to declare the variables for each message from the array that is generated.
What i need is a nested array for each message that is in the HTML. So the above example displays 2 arrays but it could be 54 for example.
Code i use to generate normal array:
adiv.innerHTML = cleanupDocString;
trs = adiv.querySelectorAll('tr[bgcolor="#FFFFFF"]');
trs.forEach(function(tr) {
var d = [];
tr.querySelectorAll("td")
.forEach(function(td) {
var img = td.querySelector("img"),
src = img && img.attributes.getNamedItem("src").value;
d.push(src || td.textContent);
});
msgs.push(d);
});
The code above puts this out in console (this example has 2 messages inside it, there are also arrays with 54 messages):
0:Array(6)
0:"2017-08-31T00:00:00"
1:"13:22"
2:"MessageType"
3:ā€¯ClientName"
4:"Subject "
5:"messageText"
length:6
proto:Array(0)
1:Array(6)
0:"2017-08-31T00:00:00"
1:"13:21"
2:" MessageType "
3: "ClientName"
4:" Subject "
5:" messageText "
lenth:6
proto:Array(0)
To make the question easier:
I need to know how i can put the data into a variable that i fetch from the array above. I just don't know how to do it so its dynamic.
What i tried:
var messageDate = msgs[0][0];
var messageTime = msgs[0][1];
var messageType = msgs[0][2];
var messageClient = msgs[0][3];
var messageSubject = msgs[0][4];
var messageText = msgs[0][5];
The above code works but only fetches the first message. I need all the messages that are on the page that is provided. I tried using a ID in the first [] but that also didn't give me the desired result.
Thanks for your help and patience in advance.
Output and code has been slightly edited so it hides personal information
i am assuming msgs is arrray of arrays and the order of properties is guaranteed
var mappedArray = msgs.map((msg)=> {
return {
messageDate : msg[0];
messageTime : msg[1];
messageType : msg[2];
messageClient : msg[3];
messageSubject : msg[4];
messageText :msg[5];
}
})
Edit1
you can use arrayconcat
var mergedArray = mappedArray.concat(otherArray);
To transform the multidimensional array to an array of objects with the help of Array.prototype.map and a simple helper dictionary which defines the index => property mapping.
var messages = [
[
"2017-08-31T00:00:00",
"13:22",
"MessageType",
"ClientName",
"Subject",
"messageText",
"unwanted value"
],
[
"2017-08-31T00:00:00",
"13:22",
"MessageType",
"ClientName",
"Subject",
"messageText",
"unwanted value"
],
[
"2017-08-31T00:00:00",
"13:22",
"MessageType",
"ClientName",
"Subject",
"messageText",
"unwanted value"
]
];
var mappingDef = {
0: 'messageDate',
1: 'messageTime',
2: 'messageType',
3: 'messageClient',
4: 'messageSubject',
5: 'messageText'
};
function transformMessages(messages, mappingDef) {
return messages.map(function(message) {
var obj = {};
for(var index in mappingDef) {
if(mappingDef.hasOwnProperty(index)) {
obj[mappingDef[index]] = message[index];
}
}
return obj;
});
}
console.log(transformMessages(messages, mappingDef));
Related
Im trying to create a structure with Javascript as follows:
var users = {
user.id: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
user.id2: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
};
What i need: add new sessions and remove them, removing okay, but how should i define object and how can i push new sessions to user obejct? That's why key is equal to value.
If you want to use session.id1 instead of something like sessionId1 :
Assign value:
users['user.id'].['session.id1'] = value;
Create object:
var users = {
'user.id': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
'user.id2': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
};
But I don't recommend it. If you are the only one who is gonna work with this code, it's ok.
You can first create an empty object and fill it as and when the data comes like
users[user.id] = {};
For an example:
var users = {};
var user = {id : 1}; //Data received(Just an example)
users[user.id] = {};
var session = {id1 : 1.1}; //Data received
users[user.id][session.id1] = session.id1;
console.log(JSON.stringify(users));
How about refactoring the user object to store sessions as an array and push, pop and slice them as required.
var users = [
{
id:'userid',
sessions: [
{
id: 'sessionid',
sessiondata: something
},
{
id: 'sessionid',
sessiondata: something
}
]
}];
This way to can just use normal array operators on the session array for each user.
The way I'm currently generating my array of dictionaries is very hard-wired in, and I'd rather not do it that way. Top 3 doesn't necessarily have 3 items, I used that name for other reasons. For example, if I know Top 3 will contain two items in addition to the search term, it will look like this:
var top3Titles = [];
var top3Prices = [];
var top3ImgURLS = [];
var top3ItemURLS = [];
//where the title, price, and img url are sent over to the app
matchCenterItems.forEach(function(item) {
var title = item.title[0];
var price = item.sellingStatus[0].convertedCurrentPrice[0].__value__;
var imgURL = item.galleryURL[0];
var itemURL = item.viewItemURL[0];
top3Titles.push(title);
top3Prices.push(price);
top3ImgURLS.push(imgURL);
top3ItemURLS.push(itemURL);
});
// 10 results per MC Item, only showing 4 by default
var top3 =
{
"Top 3":
[
{
"Search Term": searchTerm
},
{
"Title": top3Titles[0],
"Price": top3Prices[0],
"Image URL": top3ImgURLS[0],
"Item URL": top3ItemURLS[0]
},
{
"Title": top3Titles[1],
"Price": top3Prices[1],
"Image URL": top3ImgURLS[1],
"Item URL": top3ItemURLS[1]
},
]
};
return top3;
What I want to do instead is to have the number of dictionaries after the initial Search Term depend on how many item objects there are in the matchCenterItems array. I figured I could do this using a for loop, but I'm not entirely sure how to format it for this purpose. Rather than having separate arrays for titles, prices, etc, I want it to be an object with a title property for example.
You could initialize an array inside top3 and add the objects while iterating over one or your arrays (top3Titles, top3Prices etc).
Like so:
var top3 = {'Top 3': [{'Search Term': searchTerm}]};
for (var i in top3Titles) {
top3['Top 3'].push({
'Title': top3Titles[i],
'Price': top3Prices[i],
'Image URL': top3ImgURLS[i],
'Item URL': top3ItemURLS[i]
});
}
Or, even better, you could replace everything you've posted with:
var top3 = {'Top 3': [{'Search Term': searchTerm}]};
matchCenterItems.forEach(function(item) {
top3['Top 3'].push(
{
'Title': item.title[0],
'Price': item.sellingStatus[0].convertedCurrentPrice[0].__value__,
'Image URL': item.galleryURL[0],
'Item URL': item.viewItemURL[0]
});
});
return top3;
But the point here is, the return belongs inside a function, as I've told you in my comment to your question.
I don't have good practice in JavaScript , but I can give you Demo of How to generate array of dict using for loop
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var arr=[];
var i;
var text="";
for(i=0;i<10;i++){
<!-- Creating 10 dictionary in array and initialise with some->
<!--value to check->
arr.push({firstName : "John"})
}
<!-- check that dict is working or not->
for(i=0;i<10;i++){
text=text+arr[i].firstName+'<br />'
}
document.getElementById("demo").innerHTML =
text;
</script>
</body>
</html>
you can run and check it ..
I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
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')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?
I am building a file management system for the web right now.
But I have some problems with javascript array's.
In the system there is an opportunity to add labels to file's.
In javascript I want to have the ID and the value's of the labels with the fileId in 1 array.(as below).
I also want the FileId and the LabelId not as the index of the array's. Because the FileId and labelId can be a realy high number. And then I have an array full of undefined items.
Here an example of how I would like to have it:
array[FileId][labelId,labelValue]
If you have an solution please help me.
Thanks.
You can form structure like this:
arr = [{FieldId:fid_value, Labels:[{labelId:lid_value, labelValue:label_text}]}]
Basically, an array with objects. Each object contains two fields: field id and labels.
Labels is an array with objects also. Each object has label id and label value property.
Code to create new items might be like this:
arr = array();
fieldObj = {FieldId:fid_value, Labels:[]};
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
...
arr.push(fieldObj);
I'm not entirely sure what you're asking but array within array is possible...
a = []
a.push('a')
Result:
["a"]
a.push(['hello','world'])
Result:
["a",
Array[2]
0: "hello"
1: "world"
]
It sounds like you want objects instead of arrays:
var obj = {};
obj["fieldName"] = {label: "labelname", labelId: 1234};
Then you can access this data as:
obj["fieldName"].label
You could also use an object
var data = {};
data["item1"] = { "labelId" : "foo1", "labelValue" : "bar1" };
data["item2"] = { "labelId" : "foo2", "labelValue" : "bar2" };
console.log(data.item1.labelId);
There are plenty of ways you can strcture the object, it is normally better to use an object than to remember that index 0 is the id and that index 1 is a value.
Use should use objects as well as arrays:
var root = [{
id: '12345',
metadata: {
label: 'foo',
},
type: 'folder',
name: 'Folder Name',
children: [...]
}
];
Now, you can iterate through the folders and files in your root:
for (var i = 0; i < root.length; i++) {
var item = root[i];
console.log(item.type, item.name, item.id);
}
I have a JavaScript object like this:
[{
name : "soccer",
elems : [
{name : "FC Barcelona"},
{name : "Liverpool FC"}
]
},
{
name : "basketball",
elems : [
{name : "Dallas Mavericks"}
]
}]
Now I want to search on this JavaScript object in the browser. The search for "FC" should give me something like this:
[
{name : "FC Barcelona"},
{name : "Liverpool FC"}
]
How to do this fast? Are there any JavaScript libs for this?
You might like using jLinq (personal project)
http://hugoware.net:4000/Projects/jLinq
Works like LINQ but for JSON and it allows you to extend it and modify it however you want to. There is already a bunch of prebuilt methods to check values and ranges.
Seeing as though the only helpful answers have been referencing third party libraries - here's your native javascript solution. For anyone that only wants a few lines of code rather than a stack:
The function:
Array.prototype.findValue = function(name, value){
var array = map(this, function(v,i){
var haystack = v[name];
var needle = new RegExp(value);
// check for string in haystack
// return the matched item if true, or null otherwise
return needle.test(haystack) ? v : null;
});
return array;
}
A native .map() function:
map = function(array, mapFunction) {
var newArray = new Array(array.length);
for(var i = 0; i < array.length; i++) {
newArray[i] = mapFunction(array[i]);
}
return newArray;
}
Your object:
(skimmed from your posted abject):
myObject = {
name : "soccer",
elems : [
{name : "FC Barcelona"},
{name : "Liverpool FC"}
]
},
{
name : "basketball",
elems : [
{name : "Dallas Mavericks"}
]
}
For usage:
(This will search your myObject.elems array for a 'name' matching 'FC')
var matched = myObject.elems.findValue('name', 'FC');
console.log(matched);
The result - check your console:
[Object, Object, findValue: function]
0: Object
name: "FC Barcelona"
__proto__: Object
1: Object
name: "Liverpool FC"
__proto__: Object
length: 2
__proto__: Array[0]
Try jOrder. http://github.com/danstocker/jorder
It's optimized for fast O(logn) search and sorting on large (thousands of rows) tables in JS.
As opposed to array iteration, which most of the answers here are based on, jOrder uses indexes to filter data. Just to give you an idea, free-text search on a 1000-row table completes about 100 times faster than iteration. The bigger the table, the better ratio you get.
However jOrder can't process the format of your sample data. But if you re-format it like this:
var teams =
[
{ sport : "soccer", team: "FC Barcelona" },
{ sport : "soccer", team: "Liverpool FC" },
{ sport : "basketball", team : "Dallas Mavericks"}
]
You can get the desired results by first setting up a jOrder table:
var table = jOrder(teams)
.index('teams', ['team'], { grouped: true, ordered: true, type: jOrder.text });
And then running a search on it:
var hits = table.where([{ team: 'FC' }], { mode: jOrder.startof });
And you'll get exactly the two rows you needed. That's it.
The straightforward way to do this is simply to iterate over every property of the object and apply a test function to them (in this case, value.contains("FC")).
If you want it to go faster, you'd either need to implement some kind of caching (which could be eagerly populated in the background ahead of any queries), or perhaps precalculate the result of various popular test functions.
You could do this with regular expressions performed against a serialized JSON string:
var jsonString = "[{ name : \"soccer\", elems : [ {name : \"FC Barcelona\"}"
+", {name : \"Liverpool FC\"}]},{name : \"basketball\",elems : ["
+"{name : \"Dallas Mavericks\"} ]}]";
var pattern = /\s*([\w\d_]+)\s*:\s*((\"[^\"]*(your pattern here)[^\"]*\")|(\'[^\']*(your pattern here)[^\']*\'))\s*/g;
var foundItems = [];
var match;
while(match = pattern.exec(jsonString)){
foundItems.push(match[0]);
}
var foundJSON = "[{" + foundItems.join("}, {") + "}]";
var foundArray = eval(foundJSON);
I haven't tested the loop part of this, but the Regex seems to be working well for me with simple tests in firebug.
In regards to AngularJS, you can do this:
var item = "scope-ng-model";
(angular.element('form[name="myForm"]').scope())[item] = newVal;