Related
I have an array that looks like this:
const data = [
{"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];
and I wanted to use the .filter() function in angular so when I pass in the string '2', it returns the object containing only the nested arrays which contains the string '2', in other words should return this:
[
{"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "LAST2", "total": 50}]}]},
];
I tried
let values = data.items.filter(d => d.items.forEach(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))
and it just returns an empty array,
I also tried
let values = data.items.forEach(d => d.items.filter(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))
and
let values = data.items.filter(d => d.items.every(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))
and both return undefined and an empty array.
what is the correct way to do this?
const data = [
{"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];
let searchText='TEST'
let values = JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})
console.log(values)
let values = JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})
forEach doesn't return anything, map returns the array, where each element is replaced by the return value of from the function you pass to it.Also you weren't accessing deep enough, since your target array is at data[0].items[0].items, for example. I might have missed a parenthesis or bracket here
I have the JSON like
var resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26 - 01 - 2020"
}]
}
}`;
I expect the output:
{
"total": "1",
"list_name": "title",
"name": "sonu",
"mobileno": "6543213456"
}
Here "list_name": "title" is dynamic, sometimes it will come "list_name": "book", based on that above mentioned response I want to get.
Something like this? I had to fix your invalid JSON
You can make it more clever if you study https://javascript.info/destructuring-assignment in depth
const resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26-01-2020"
}]
}
}`
const data = JSON.parse(resultJSON).data
const content = data[data.list_name];
let newObj = {}
newObj["total"] = data["total"];
newObj["list_name"] = data["list_name"];
newObj["name"] = content["name"];
newObj["mobileNo"] = content["mobileNo"];
console.log(newObj)
I have a universal variable on my website which includes line items with relevant details. These line items are reflective of what the user has in their cart. I am integrating with a third party who require the data passed through to them to be formatted slightly different. The below is the data layer currently on my website:
"lineItems": [
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo"
},
"quantity": 1
}
]
The below is what format the third party needs:
"lineItems": [
{
"sku": "s83y016b5",
"name": "Jeans",
"description": "A super great pair of jeans.",
"category": "Everyday Wear",
"other": {"fieldName": "This can be a string or any value you like"}
"unitPrice": 11.99,
"salePrice": 11.99,
"quantity": 2,
"totalPrice": 23.98
"imageUrl": "http://www.my-website.com/a/p/shirt.jpeg",
"productUrl": "http://www.my-website.com/index.php/shirt.html",
}]
Obviously this needs to be dynamic based on the products in the cart. What I intend to do is use javascript to amend the data and send this to the third party via Google Tag Manager.
Any help would be greatly appreciated. Any questions welcome.
This should be close to what you're looking for.
let oldLineItems = "your object";
let newLineItems = {};
newLineItems.lineItems = [];
for (let i in oldLineItems.lineItems) {
newLineItems.lineItems[i] = {};
for (let key in oldLineItems.lineItems[i].product)
{
newLineItems.lineItems[i][key] = oldLineItems.lineItems[i].product[key];
}
}
See code below.
I'm not sure how your lineItems object is set up, but below I just created an array called line Items. If line items is a key in an object which I suspect from your snippet above, you will have to go a level deeper in the for loops used in my example below.
Simply add further details to the new object in the nested for in loops below.
var lineItems =
[
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 1
},
{
"product": {
"id": "s83y01699",
"sku_code": "s83y01699",
"url": "/en-gb/pants/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/pants.jpeg",
"name": "Pants",
"manufacturer": "",
"category": "Casual Wear",
"stock": 90,
"currency": "au",
"unit_sale_price": 14,
"unit_price": 14,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 14
},
];
var newLineItems = [];
for(var char in lineItems){
// Adding some values to newLineItems.
newLineItems.push({
sku: lineItems[char].product.sku_code,
name: lineItems[char].product.name,
description: lineItems[char].product.description,
category: lineItems[char].product.category,
quantity: lineItems[char].quantity
});
}
console.log(JSON.stringify(newLineItems));
I have a json similar to this one
{
"id": "1",
"month": "January",
"type": "inc",
"Value": "780.00",
"year": "2018",
},
{
"id": "2",
"month": "January",
"type": "inc",
"Value": "80.00",
"year": "2018",
},
{
"id": "3",
"month": "February",
"type": "inc",
"Value": "100.00",
"year": "2018",
},...
Now I need to get all the Value from the object for all the months, as you can see I may have more objects with the same month name. The closer I got to was creating 2 arrays 1 with the list of Months and 1 with the value but I got stuck, can someone lead me to the correct path?
The desired output would be to get an array like that ["January"=>1500, "February"=>2000...] or have 2 arrays, 1 with the list of months where there is income (I already have it) and the second the total income for these months, so it's like this: ["January", "February", "March"..] and the second one [1500, 2000, 300...]
You can use the function Array.prototype.reduce to sum each Value by month.
let arr = [{ "id": "1", "month": "January", "type": "inc", "Value": "780.00", "year": "2018", }, { "id": "2", "month": "January", "type": "inc", "Value": "80.00", "year": "2018", }, { "id": "3", "month": "February", "type": "inc", "Value": "100.00", "year": "2018", }],
result = arr.reduce((a, {month, Value}) => {
a[month] = (a[month] || 0) + +Value;
return a;
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I actually can barely understand what you would like to achieve. Please provide some example.
If I understood you correctly, you can use map function of js array to map each object to its Value.
let arr = [...];
console.log(arr.map(item => item.Value));
You can do
var fabuaryDate = yourdata
.filter(function(data) { return data.month == "February" })
.map(function(x){return {value: x.Value} })
To get result in following format :
{
jan : [1,2,3],
feb : [3,4,5,6],
april : [3,4,5]
}
do this :
var output = {}
arr.forEach(element => {
if(!output[element.month]){
output[month] = new Array();
}
output[month].push(element.value);
});
You can iterate the object and fill an array with the values of the field you want to extract, like so:
const data = [ {
"id": "1",
"month": "January",
"type": "inc",
"Value": 780.00,
"year": "2018",
},
{
"id": "2",
"month": "January",
"type": "inc",
"Value": 80.00,
"year": "2018",
},
{
"id": "3",
"month": "February",
"type": "inc",
"Value": 100.00,
"year": "2018",
}];
let dataArray = data.reduce((accum, d) => {
if(!accum[d.month]) accum[d.month] = 0;
accum[d.month] += d.Value;
return accum;
},{});
console.log(dataArray);
Although you don't seem to be clear enough with what have you tried here is an example of what you could do in order to read all the values inside the json.
function myFunction(item) {
console.log(item.month + " with the value " + item.Value)
}
var jsonArray = [{"id": "1","month": "January", "type": "inc", "Value": "780.00", "year": "2018" }, { "id": "2", "month": "January", "type": "inc", "Value": "80.00", "year": "2018" }, { "id": "3", "month": "February", "type": "inc", "Value": "100.00", "year": "2018" }];
jsonArray.forEach(myFunction);
Since you're working with an array of objects you must access to each of the objects in the array and then get the attribute that you require.
Hope this help, have a great day.
I have been trying to get nested json data inside columns. The json structure is:
[{
"ratings": [{
"rating": "Detractor",
"employees": [{
"empName": "Pavan",
"quarters": [{
"quarterName": "q1 2015",
"weeks": [{
"weekName": "week1",
"month": "January",
"points": [{
"0": "point1"
}, {
"1": "point2"
}]
}
, {
"weekName": "week2",
"month": "January",
"points": [{
"0": "point1"
}, {
"1": "point2"
}]
}, {
"weekName": "week3",
"month": "January",
"points": [{
"0": "point1"
}, {
"1": "point2"
}]
}
]
}, {
"quarterName": "q2 2015",
"weeks": [{
"weekName": "week4",
"month": "January",
"points": [{
"0": "point1"
}, {
"1": "point2"
}]
}
, {
"weekName": "week5",
"month": "January",
"points": [{
"0": "point1"
}, {
"1": "point2"
}]
}, {
"weekName": "week6",
"month": "January",
"points": [{
"0": "point1"
}, {
"1": "point2"
}]
}
]
}]
}]
}
]
}]
The output should have rating in one column, the corresponding employees in the next and the points in the third column.
I found a solution here, but it deals with only one level and I could not extend it to multiple levels.
I need to display weekly data.
Expected Output
There is no problem accessing nested objects in ui-grid, generally speaking.
In your case the problem seems to be more related to the fact that you have a dynamic structure.
In ui-grid you can assign a value to a column with a string containing the full path for that value, for example:
Suppose you assing ratings sub-array to gridOptions.data, the value of field for week1, week2 and week4 would respectively be:
'employees[0].quarters[0].weeks[0].points[0]'
'employees[0].quarters[0].weeks[1].points[0]'
'employees[0].quarters[1].weeks[0].points[0]'
Now, add to it that the number of weeks and quarters is not fixed and you will find that there is no direct way to programmatically relate the number of the week to the index needed for weeks and quarters array.
I think the best way to handle this would be iterate through the original data you receive and build a new JSON more suited for the grid.
In pseudo code you could do something like this:
initialize results array
iterate through ratings
create new empty object (current_object)
add current_object to results array
iterate through employees
iterate through quarters
iterate through weeks
add value for i-th week as week_i to current_object