Related
I am looking to solve 2 problems here
Group the orders to create an items array based on based on orderNo
Include the tracking-information from the tracking array in tracking.json into the orders array.
So far I have only managed to get started with the grouping.
//orders.json
const orders = [
{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "A",
"articleImageUrl": "watch.jpg",
"quantity": 1,
"product_name": "Watch"
},
{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "B",
"articleImageUrl": "belt.jpg",
"quantity": 2,
"product_name": "Belt"
},
{
"orderNo": "2",
"tracking_number": "002",
"courier": "FedEx",
"street": "637 Britannia Drive",
"zip_code": 94591,
"city": "Vallejo",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "",
"articleImageUrl": "",
"quantity": "",
"product_name": ""
}
];
//tracking.json
const tracking = [{
"tracking_number": "001",
"location": "",
"timestamp": "2018-04-01T00:00:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
},
{
"tracking_number": "002",
"location": "",
"timestamp": "2018-04-06T05:58:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
}
]
//expected output data.json
const data = [
{
"orderNo":"1",
"tracking_number":"001",
"courier":"FedEx",
"street":"1745 T Street Southeast",
"zip_code":"20020",
"city":"Louisville",
"destination_country":"USA",
"email":"test#test.com",
"articleNo":"A",
"articleImageUrl":"watch.jpg",
"quantity":"1",
"product_name":"Watch",
"items":[
{
"articleNo":"A",
"articleImageUrl":"watch.jpg",
"quantity":"1",
"product_name":"Watch"
},
{
"articleNo":"B",
"articleImageUrl":"belt.jpg",
"quantity":"2",
"product_name":"Belt"
}
],
"tracking":{
"tracking_number":"001",
"location":null,
"timestamp":"2018-04-01T00:00:00.000Z",
"status":"Scheduled",
"status_text":"Order processed",
"status_details":"The order has been processed."
}
},
{
"orderNo": "2",
"tracking_number": "002",
"courier": "FedEx",
"street": "637 Britannia Drive",
"zip_code": 94591,
"city": "Vallejo",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "",
"articleImageUrl": "",
"quantity": "",
"product_name": "",
"items":[
],
"tracking":{
"tracking_number": "002",
"location": "",
"timestamp": "2018-04-06T05:58:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
}
}
]
const groupBy = key => array =>
array.reduce(
(objectsByKeyValue, obj) => ({
...objectsByKeyValue,
[obj[key]]: (objectsByKeyValue[obj[key]] || []).concat(obj)
}),
{}
);
const groupByOrders = groupBy('orderNo');
I am looking to get the data in the format shown in data.json
This is the current code along with the data
Code
Below is one possible way to achieve the target.
Code Snippet
const groupAndInclude = (base, delta) => {
const result = []; // result array
base.forEach( // iterate over the "orders"
({ // de-structure to directly access specific props
orderNo, tracking_number, articleNo,
articleImageUrl, quantity, product_name,
...rest // remaining props not directly-accessed
}) => {
const foundOrder = result.find( // find if "order" already in "result"
ob => ob.orderNo === orderNo
);
if (foundOrder) { // found a match, simply push "article"-info
if (articleNo.length > 0) { // push to "items" only if not "empty"
foundOrder.items.push({ // to the "items" array
articleNo, articleImageUrl, quantity, product_name
})
}
} else { // match not-found. Add new entry to "result"
const resObj = { // construct the result-object "resObj"
...rest, orderNo // using all relevant "order" props
};
if (articleNo.length > 0) { // do not add "empty" item
resObj.items = [{ // add "items" as an array
articleNo, articleImageUrl, quantity, product_name
}];
} else {
resObj.items = [];
};
const foundTracker = delta.find( // look for "tracking_number"
ob => ob.tracking_number === tracking_number
);
// if "tracking_number" found, add to result-object
if (foundTracker) resObj.tracking = {...foundTracker};
result.push(resObj); // push the result-object to the "result" array
}
}
);
return result; // explicitly return the "result" array
};
const orders = [{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "A",
"articleImageUrl": "watch.jpg",
"quantity": 1,
"product_name": "Watch"
},
{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "B",
"articleImageUrl": "belt.jpg",
"quantity": 2,
"product_name": "Belt"
},
{
"orderNo": "2",
"tracking_number": "002",
"courier": "FedEx",
"street": "637 Britannia Drive",
"zip_code": 94591,
"city": "Vallejo",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "",
"articleImageUrl": "",
"quantity": "",
"product_name": ""
}
];
//tracking.json
const tracking = [{
"tracking_number": "001",
"location": "",
"timestamp": "2018-04-01T00:00:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
},
{
"tracking_number": "002",
"location": "",
"timestamp": "2018-04-06T05:58:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
}
];
console.log(groupAndInclude(orders, tracking));
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added in the snippet above.
You could take two objects as reference to same orderNo and tracking_number.
For adding an oder to the result set remove item properties and take a new object of this properties.
const
orders = [{ orderNo: "1", tracking_number: "001", courier: "FedEx", street: "1745 T Street Southeast", zip_code: 20020, city: "Louisville", destination_country: "USA", email: "test#test.com", articleNo: "A", articleImageUrl: "watch.jpg", quantity: 1, product_name: "Watch" }, { orderNo: "1", tracking_number: "001", courier: "FedEx", street: "1745 T Street Southeast", zip_code: 20020, city: "Louisville", destination_country: "USA", email: "test#test.com", articleNo: "B", articleImageUrl: "belt.jpg", quantity: 2, product_name: "Belt" }, { orderNo: "2", tracking_number: "002", courier: "FedEx", street: "637 Britannia Drive", zip_code: 94591, city: "Vallejo", destination_country: "USA", email: "test#test.com", articleNo: "", articleImageUrl: "", quantity: "", product_name: "" }],
tracking = [{ tracking_number: "001", location: "", timestamp: "2018-04-01T00:00:00.000Z", status: "OrderProcessed", status_text: "Order processed", status_details: "The order has been processed." }, { tracking_number: "002", location: "", timestamp: "2018-04-06T05:58:00.000Z", status: "OrderProcessed", status_text: "Order processed", status_details: "The order has been processed." }],
keys = ["articleNo", "articleImageUrl", "quantity", "product_name"],
items = {},
trackings = {},
result = [];
for (let order of orders) {
const item = {};
for (const key of keys) {
let value;
({ [key]: value, ...order } = order);
item[key] = value;
}
if (!items[order.orderNo]) result.push(items[order.orderNo] = { ...order, items: [] });
if (Object.values(item).some(Boolean)) items[order.orderNo].items.push(item);
trackings[order.tracking_number] = items[order.orderNo];
}
for (const transfer of tracking) trackings[transfer.tracking_number].tracking = transfer;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This the data i need this value only email": "gm#gmail.com"
{
"params": {
"user": {
"address1": "790 7th Ave",
"address2": "hhhdkhdskhsdkh",
"city": "Chennai",
"name": "gm4",
"phone": "",
"state": "TN",
"zipcode": "600008"
},
"query": {
"FILTERS": [
[
{
"EQ": {
"email": "gm#gmail.com"
}
}
]
],
"PAGENUM": 1,
"PAGESIZE": 100,
"SELECTCOLUMNS": [],
"SORT": []
},
"trigger": "User::UserUpdated"
},
"context": {}
}
actually, I tried const out = req.params.query.FILTERS[0].EQ.email
but i field unable to get expect result plz help.
It is a nested array.
req.params.query.FILTERS[0][0].EQ.email
I'm struggling with converting the nested JSON array that I have.
{
"Id": "1234",
"Company": {
"element": [{
"Name": "htc",
"Contacts": {
"element": [{
"name": "john",
"phone": "1234"
}, {
"name": "peter",
"phone": "5678"
}]
},
"Address": {
"element": {
"country": "us",
"state": "cali"
}
}
}, {
"Name": "samsung",
"Contacts": {
"element": [{
"name": "luke",
"phone": "0011"
}, {
"name": "james",
"phone": "2233"
}]
},
"Address": {
"element": {
"country": "us",
"state": "texas"
}
}
}]
}
}
As you'll notice, there's this "element" in the arrays "Company", "Contacts" and "Address". But the output that I need to provide should not contain the "element" such as this code:
{
"Id": "1234",
"Company": [{
"Name": "htc",
"Contacts": [{
"name": "john",
"phone": "1234"
}, {
"name": "peter",
"phone": "5678"
}],
"Address": [{
"country": "us",
"state": "cali"
}]
}, {
"Name": "samsung",
"Contacts": [{
"name": "luke",
"phone": "0011"
}, {
"name": "james",
"phone": "2233"
}],
"Address": [{
"country": "us",
"state": "texas"
}]
}]
}
I have no clue how to do in JavaScript. Any ideas/tips are appreciate.
Thank you
You can try something like this:
var data={Id:"1234",Company:{element:[{Name:"htc",Contacts:{element:[{name:"john",phone:"1234"},{name:"peter",phone:"5678"}]},Address:{element:{country:"us",state:"cali"}}},{Name:"samsung",Contacts:{element:[{name:"luke",phone:"0011"},{name:"james",phone:"2233"}]},Address:{element:{country:"us",state:"texas"}}}]}};
var keysToClean = ["Address", "Contacts"]
// Copy object instead of reference
var result = Object.assign({}, data);
result.Company = result.Company.element;
result.Company.forEach(x => {
keysToClean.forEach(k => {
x[k] = Array.isArray(x[k]) ? x[k].element : [x[k].element]
})
})
console.log(result);
Note: I have use Object.create and Arrow functions. They are not supported by old browsers. You can refer to following link for alternative to deep copy an object:
What is the most efficient way to deep clone an object in JavaScript?
The solution using Array.prototype.forEach() function:
var companyData = { "Id": "1234", "Company": { "element": [{ "Name": "htc", "Contacts": { "element": [{ "name": "john", "phone": "1234" }, { "name": "peter", "phone": "5678" }] }, "Address": { "element": { "country": "us", "state": "cali" } } }, { "Name": "samsung", "Contacts": { "element": [{ "name": "luke", "phone": "0011" }, { "name": "james", "phone": "2233" }] }, "Address": { "element": { "country": "us", "state": "texas" } } }] }
};
companyData.Company = companyData.Company.element;
var omitElement = function(o){
if (!o['element']) return o;
return (Array.isArray(o.element))? o.element : [o.element];
}
companyData.Company.forEach(function (o) {
o.Contacts = omitElement(o.Contacts);
o.Address = omitElement(o.Address);
});
console.log(companyData);
Please see this Plunker This should help.. it will generate desired result you need but be aware this is just a way to do this, and only meant for information purpose. It's not production grade...
function ParseData(data)
{
var newObject={Id:0, Company:[]};
newObject["Id"]=data["Id"];
newObject["Company"]=CreateCompanyObject(data["Company"]["element"]);
console.log(JSON.stringify(newObject));
}
function CreateCompanyObject(data)
{
var companies=[];
for(var i=0;i<data.length;i++)
{
companies.push({
name:data[i].Name,
contacts:CreateContactObject(data[i].Contacts.element),
Address:CreateAddressObject(data[i].Address.element)});
};
return companies;
}
function CreateContactObject(data){
var contacts=[];
for(var i=0;i<data.length;i++)
contacts.push(data[i]);
return contacts;
}
function CreateAddressObject(data){
var address=[];
if(typeof(data)=="array"){
for(var i=0;i<data.length;i++)
address.push(data[i]);
}
else
address.push(data);
return address;
}
You could check for element and move the content a step ahead to its parent.
function deleteElement(object){
Object.keys(object).forEach(function (k) {
if (object[k] && typeof object[k] === 'object') {
if ('element' in object[k]) {
object[k] = Array.isArray(object[k].element) ?
object[k].element :
[object[k].element];
}
deleteElement(object[k]);
}
});
}
var data = { Id: "1234", Company: { element: [{ Name: "htc", Contacts: { element: [{ name: "john", phone: "1234" }, { name: "peter", phone: "5678" }] }, Address: { element: { country: "us", state: "cali" } } }, { Name: "samsung", Contacts: { element: [{ name: "luke", phone: "0011" }, { name: "james", phone: "2233" }] }, Address: { element: { country: "us", state: "texas" } } }] } };
deleteElement(data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have some problem with here jquery here. So I want to make an autocomplete text field using json object from database, here I provide my code
jQuery :
$('#school_name').autocomplete({
minLength: 3,
autoFocus: true,
source: function(request, response) {
$.getJSON('https://host/path', { q: $('#school_name').val() },
response);
}
Return Json
{
"status": "success",
"result": {
"data": [
{
"school_id": xxx,
"school_name": "xxx",
"status": "Swasta",
"address": "xxx",
"city": "BANYUWANGI",
"province": "JAWA TIMUR",
"phone": "1234",
"email": "xx#a.co",
"picture": null,
"is_published": "Y"
},
{
"school_id": xxx,
"school_name": "xxx",
"status": "Swasta",
"address": " ",
"city": "",
"province": "",
"phone": "-",
"email": null,
"picture": null,
"is_published": "Y"
}
]
}
}
I dont want return value json object like i've got, I only need school_name in array form, please help me to solve my problem
Use response callback to push data you want.
$('#school_name').autocomplete({
minLength: 3,
autoFocus: true,
source: function(request, response) {
$.get('https://host/path').always(function(res) {
var json = JSON.parse(res), result_arr = [];
$.each(json.result.data, function(k,v) {
result_arr.push(v.school_name);
});
response(result_arr);
});
}
});
You can use Array.prototype.map to transform an array. map will run a function over each item in the array and create a new array with the returned values.
const json = {
"status": "success",
"result": {
"data": [
{
"school_id": '1234',
"school_name": "First School Name",
"status": "Swasta",
"address": "xxx",
"city": "BANYUWANGI",
"province": "JAWA TIMUR",
"phone": "1234",
"email": "xx#a.co",
"picture": null,
"is_published": "Y"
},
{
"school_id": '5678',
"school_name": "Second School Name",
"status": "Swasta",
"address": " ",
"city": "",
"province": "",
"phone": "-",
"email": null,
"picture": null,
"is_published": "Y"
}
]
}
}
console.log(
json.result.data.map(school => school.school_name)
)
I have many structures like:
student :
name: SomeName
city : someSity
school : someschool
date : somedate
What I want is to sort them in a way like (with test data):
Sorted_map:
city : NY
school: School1
name:Name1
name: Name2
name: Name4
shool: School2
name:Name11
name: Name21
name: Name41
city: WDC
school: School3
name: Name22
name: Name29
What I did is sorting by city :
function groupBy( array , f ) {
var groups = {};
array.forEach( function( o )
{
var group = JSON.stringify( f(o) );
groups[group] = groups[group] || [];
groups[group].push( o );
});
return groups;
}
var result = groupBy(sudentsItems, function(item)
{
return unifyCity(item.city);
}
so now it is sorted only by the "city" key. How do I sort data inside city?
I guess I need something like Map < city_key, Map < school_key, name > >;
Data sample :
[{
"name": "John Some",
"city": "NY",
"school": "NY Central",
"date": 1460986261733
}, {
"name": "Sarah Mil",
"city": "Moscow",
"school": "Moscow Central",
"date": 1460986201733
}, {
"name": "John Again",
"city": "NY",
"school": "NY Central",
"date": 1460986261733
}, {
"name": "Kit Parcer",
"city": "NY",
"school": "NY Central",
"date": 1460086261733
}, {
"name": "Anna Love",
"city": "SPB",
"school": "SPB Central",
"date": 1460983261733
}]
It looks like that you are looking either for sorted or a grouped data.
var data = [{ "name": "John Some", "city": "NY", "school": "NY Central", "date": 1460986261733 }, { "name": "Sarah Mil", "city": "Moscow", "school": "Moscow Central", "date": 1460986201733 }, { "name": "John Again", "city": "NY", "school": "NY Central", "date": 1460986261733 }, { "name": "Kit Parcer", "city": "NY", "school": "NY Central", "date": 1460086261733 }, { "name": "Anna Love", "city": "SPB", "school": "SPB Central", "date": 1460983261733 }],
object = {};
data.sort(function (a,b) {
return a.city.localeCompare(b.city) ||
a.school.localeCompare(b.school) ||
a.name.localeCompare(b.name);
});
data.forEach(function (a) {
object[a.city] = object[a.city] || {};
object[a.city][a.school] = object[a.city][a.school] || [];
object[a.city][a.school].push(a.name);
});
document.write('<pre>data sorted: ' + JSON.stringify(data, 0, 4) + '</pre>');
document.write('<pre>data grouped: ' + JSON.stringify(object, 0, 4) + '</pre>');
You can use a for-loop to iterate over all the fields in the sorters array. If, at any point, the result of the comparison is not 0 (equal) then immediately return the value.
function sortMulti(data, sorters) {
return data.sort(function(a, b) {
for (var i = 0; i < sorters.length; i++) {
var result = 0;
var f1 = a[sorters[i].field];
var f2 = b[sorters[i].field];
if (typeof f1 === 'string' || typeof f2 === 'string') {
result = f1.localeCompare(f2);
} else {
result = f1 < f2 ? -1 : f1 > f2 ? 1 : 0;
}
if (sorters[i].direction === 'desc') {
result = result * -1;
}
if (result !== 0) {
return result;
}
}
});
}
var data = [
{ "name": "John Some", "city": "NY", "school": "NY Central", "date": 1460986261733 },
{ "name": "Sarah Mil", "city": "Moscow", "school": "Moscow Central", "date": 1460986201733 },
{ "name": "John Again", "city": "NY", "school": "NY Central", "date": 1460986261733 },
{ "name": "Kit Parcer", "city": "NY", "school": "NY Central", "date": 1460086261733 },
{ "name": "Anna Love", "city": "SPB", "school": "SPB Central", "date": 1460983261733 }
];
var sorters = [
{ field: 'city', direction: 'asc' },
{ field: 'school', direction: 'asc' },
{ field: 'name', direction: 'asc' }
];
document.body.innerHTML = '<pre>' + JSON.stringify(sortMulti(data, sorters), null, 4) + '</pre>';