I have two arrays of strings: hrefs, thumbs. Need to combine this arrays into another array with structure like below. How to do that ? For clarity - i need to use Lightview API to call function Lightview.show(elements), where elements is result array i need to build.
HTML:
one
two
three
Arrays:
var hrefs = $('.lv').map(function() { return $(this).attr('href'); }).get();
var thumbs = $('.lv').map(function() { return $(this).attr('thumbnail'); }).get();
The desired result array (elements):
{
{hrefs[0],
{
thumbnail: thumbs[0]
}
},
{hrefs[1],
{
thumbnail: thumbs[1]
}
},
...
}
I've started with this, but i think it is something wrong...
var e = new Array();
$.each(hrefs, function(i, value) {
e[i] = new Array();
e[i][0] = value;
e[i][1] = {thumbnail: thumbs[i]};
});
Do you mean this?
var result = $('.lv').map(function() {
var o = {};
o[$(this).attr('href')] = { thumbnail: $(this).attr('thumbnail') } };
return o;
}).get();
Are you looking for something like this?
var hrefs = $('.lv').map(function() { return $(this).attr('href'); }).get();
var thumbs = $('.lv').map(function() { return $(this).attr('thumbnail'); }).get();
var arr = {};
for (i in hrefs) {
arr[hrefs[i]] = {
thumbnail: thumbs[i]
}
}
Another suggestion, with minimal use of JQuery for faster execution
var lvs = $('.lv');
var arr = {};
for (i=0; i< lvs.length; i++) {
arr[lvs[i].getAttribute('href')] = {
thumbnail: lvs[i].getAttribute('thumbnail')
}
}
You're almost there. Just do:
var e = [];
$.each(hrefs, function(i, value) {
e[i] = [];
e[i] = [ value, {thumbnail: thumbs[i]} ];
});
Or even shorter:
var e = [];
$.each(hrefs, function(i, value) {
e[i] = [ value, {thumbnail: thumbs[i]} ];
});
Try this
var result = {};
$.each( hrefs, function ( index ) {
result[ hrefs[ index ] ] = { thumbnail: thumbs[ index ] };
});
Related
I have the following JSON object and wanted to merge them by OrderID, making the items into array of objects:
[
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
]
and I'm wondering how in Javascript to merge the items on the same order...like this:
[{
"OrderID": "999123",
"Items": [{
"ItemCode": "DY-FBBO",
"ItemQuantity": "2",
"ItemName": "DOIY Foosball Bottle Opener > Red",
"ItemPrice": "34.95"
}, {
"ItemCode": "TED-072",
"ItemQuantity": "1",
"ItemName": "Ted Baker Womens Manicure Set",
"ItemPrice": "74.95"
}]
}]
I suggest you use javascript library like underscorejs/lazyjs/lodash to solve this kind of thing.
Here is the example on using underscorejs:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}]
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
Working example:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}];
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
This should do what you want it to do, but it's rather a group function than a merge function :)
You can see the result in the browser console.
var items = [
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
];
function groupBy(ungrouped, groupByProperty) {
var result = [],
getGroup = function (arr, val, groupByProperty) {
var result, j, jlen;
for (j = 0, jlen = arr.length; j < jlen; j++) {
if (arr[j][groupByProperty] === val) {
result = arr[j];
break;
}
}
if (!result) {
result = {};
result.items = [];
result[groupByProperty] = val;
arr.push(result);
}
return result;
}, i, len, item;
for (i = 0, len = ungrouped.length; i < len; i++) {
item = getGroup(result, ungrouped[i][groupByProperty], groupByProperty);
delete ungrouped[i][groupByProperty];
item.items.push(ungrouped[i]);
}
return result;
}
var grouped = groupBy(items, 'OrderID');
document.getElementById('result').innerHTML = JSON.stringify(grouped);
console.log(grouped);
<div id="result"></div>
Lodash is a great Javascript Utility library that can help you in this case. Include the latest version of lodash in your code and group the objects like this:
var mergedOrders = _.groupBy(OriginalOrders, 'OrderID');
It seems you'll have to do a function that, for each entry, will check if it match
try this :
// your array is oldArr
var newArr = []
for (var i=0;i<oldArr.length;i++){
var found = false;
for(var j=0;j<newArr.length;j++){
if(oldArr[i]["OrderID"]==newArr[j]["OrderID"]){
newArr[j]["Items"].push(oldArr[i]);
found=true;
break;
}
if(!found){
newArr.push({"OrderID" : oldArr[i]["OrderID"], "Items" : oldArr[i]});
}
}
You need to loop and create new grouped objects according to your requirement.
For an easier approach I would suggest using jquery-linq
var qOrderIds = $.Enumerable.From(myArray).Select(function(item) { return item.OrderID; }).Distinct();
var groupedList = qOrderIds.Select(function(orderId) {
return {
OrderID: orderId,
Items : $.Enumerable.From(myArray).Where(function(item) { item.OrderID === orderId}).ToArray()
};
}).ToArray();
Thank you for all your answers.
I was able to attain my goal (maybe a bit dirty and not as beautiful as yours but it worked on my end). Hoping this might help others in the future:
function processJsonObj2(dataObj, cfg) {
var retVal = dataObj.reduce(function(x, y, i, array) {
if (x[cfg.colOrderId] === y[cfg.colOrderId]) {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
delete x[cfg.colOrderId];
delete y[cfg.colOrderId];
delete x[cfg.colAddressee];
delete y[cfg.colAddressee];
delete x[cfg.colCompany];
delete y[cfg.colCompany];
delete x[cfg.colAddress1];
delete y[cfg.colAddress1];
delete x[cfg.colAddress2];
delete y[cfg.colAddress2];
delete x[cfg.colSuburb];
delete y[cfg.colSuburb];
delete x[cfg.colState];
delete y[cfg.colState];
delete x[cfg.colPostcode];
delete y[cfg.colPostcode];
delete x[cfg.colCountry];
delete y[cfg.colCountry];
delete x[cfg.colOrderMessage];
delete y[cfg.colOrderMessage];
delete x[cfg.colCarrier];
delete y[cfg.colCarrier];
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ x, y ];
return orderObj;
} else {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
var itemCode = x[cfg.colItemCode];
var itemQuantity = x[cfg.colItemQuantity];
var itemName = x[cfg.colItemName];
var itemPrice = x[cfg.colitemPrice];
var item = {};
item[cfg.colItemCode] = itemCode;
item[cfg.colItemQuantity] = itemQuantity;
item[cfg.colItemName] = itemName;
item[cfg.colItemPrice] = itemPrice;
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ item ];
return orderObj;
}
});
return retVal;
}
I am working on this demo. How can I add each selected row as an array into the data [] so that it looks like this:
[{"Cell phone":"BlackBerry Bold 9650","Rating":"2/5","Location":"UK"},
{"Cell phone":" Samsung Galaxy","Rating":"3/5","Location":"US"}]
Here is the code I have:
var data = [];
function myfunc(ele) {
var values = new Array();
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
values.push($(this).text());
});
alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
check if this works,
here is the fiddle demo
var data = [];
function myfunc(ele) {
var values = [];
var keys = [];
$.each($("input[name='case[]']:checked").closest("table").find('th'),
function () {
keys.push($(this).text());
});
keys.shift(); // to remove the first key
var len = keys.length, obj={}, ctr=0;
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
obj[keys[ctr]]=$(this).text();
ctr++;
if(ctr==len){
values.push(obj);
obj={};
ctr=0;
}
});
alert("val---" + JSON.stringify(values));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
http://jsfiddle.net/ugdas2em/
Try this:
var data = {};
function myfunc(ele) {
//var values = new Array();
var k = 0;
var j = 0;
data[k] = {};
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
if(j==3)
{
k = k+1;
data[k] = {};
j = 0;
}
//values.push($(this).text());
data[k][j] = $(this).text();
j=j+1;
});
console.debug(data);
//alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
Note: If you want then you can use [] with data variable in place of {} in my code. You need to replace at three place. Thanks.
I am pretty new to javascript and jquery. I currently have a xml file that I'm trying to parse by using jquery and javascript, but for some reason the values that I store on the array are not being saved.
var categories = new Array(); // Array for the categories
var data = {
categories: []
};
var sources = [
{
src:'',
title: '',
desc: ''
}];
var i = 0;
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
sources[i] = [];
sources[i].src = el.find('media\\:content, content').attr('url');
sources[i].title = el.find("title").text();
sources[i].desc = 'Moscone Center';
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
}
i++;
});
});
If i do console.log(categories) it prints all the categories on the array but if I do console.log(categories.length) I keep getting 0...
console.log(categories.length); // This should be outputting 5 but I keep getting 0 for the size.
for (var i=0; i<categories.length; i++) {
var category = {
name: categories[i],
videos: []
};
}
I appreciate any help that anybody can give me. Thanks
$.get function is asynchronous so you should try putting the logging inside the callback function.
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
....
});
console.log(categories.length);
});
may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);
i want to create a structure like that:
[{title:'Imágenes', extensions:'jpg,gif,png'}, {title:'Todos', extensions:'*'}]
but i need to create it from a string, in this way (in "js+jquery+php rare mode"):
items = 'Imágenes jpg,gif,png|Todos *'.split('|').each(function() {
list(title, ext) = explode(' ', $this);
filters[] = array('title' => title, 'ext' => ext);
});
i found structures like:
var theStatus = new Object();
function testIt() {
theStatus.Home = 'mouseover';
theStatus['Place'] = 'click';
for (var i in theStatus)
{
alert('theStatus[\''+i+'\'] is ' + theStatus[i])
}
}
and like:
$.alerts = {
verticalOffset: -75,
horizontalOffset: 0,
repositionOnResize: true,
overlayOpacity: .01,
overlayColor: '#FFF'
}
but i cant do nothing functional.
Thanks in advance.
This is how I would do it:
items = 'Imágenes jpg,gif,png|Todos *'.split("|").map(function (itemString) {
var parts = itemString.split(" ");
return { title: parts[0], extensions: parts[1] };
});
Or you can do this if you use jQuery and need to support older browsers:
items = $.map('Imágenes jpg,gif,png|Todos *'.split("|"), function () {
var parts = this.split(" ");
return { title: parts[0], extensions: parts[1] };
});
Your pseudocode is close.
Try the following vanilla javascript:
var str = 'Imágenes jpg,gif,png|Todos *';
var objs = str.split('|');
var objects = [];
for (var i = 0; i < objs.length; i++) {
var parts = objs[i].split(' ');
objects.push({ title: parts[0], extensions: parts[1] });
}
// objects is now an array of custom objects in the format you specified.