I want to delete items from my array where the price is lower than 20
This is my array:
[
{
"suggested_price": 50,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 50,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
}
]
and if the suggested_price is lower than 20, i will delete that out of my array list
I tried to find how on the internet but couldn't find how :/
Only find sorting array by price
You want to use filter.
const items = [{
suggested_price: 19,
suggested_price_floor: 0,
name: 'Itemname',
image: 'link',
wear: null,
color: 'ffbb00',
id: 6039365
},
{
suggested_price: 50,
suggested_price_floor: 0,
name: 'Itemname',
image: 'link',
wear: null,
color: 'ffbb00',
id: 6039365
}
];
const reducedItems = items.filter(item => (item.suggested_price > 20));
console.log(reducedItems)
;
you can use array.filter, which will create a new array with the condition passed on the filter function
var res = [
{
"suggested_price": 50,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 6,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 15,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 34,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
}
]
// instead of 30 you can replace with your value
let filteredArray = res.filter(o => o.suggested_price > 30)
console.log("filtered Array greater than 30", filteredArray)
// addition if you want to reduce the array , you can do the below
let totalOfSuggPrice = filteredArray.reduce((a,c) => ({total: a.suggested_price + c.suggested_price}))
console.log("sum of the filtered array - total of the suggested price",totalOfSuggPrice )
Related
I have a JSON object which has multiple children and grandchildren I want to get the sum of grandchildren and show it with the children, similar get the sum of children and show it with the parent.
So in the end, the parent should display the sum of all children.
{
"id": 4,
"Nominal": "4",
"name": "Revenue",
"type": "Revenue",
"parent_id": 0,
"children": [
{
"id": 14,
"Nominal": "41",
"name": "Operational Revenue",
"parent_id": 4,
"transactions_sum_debit": null,
"transactions_sum_credit": null,
"children": [
{
"id": 46,
"Nominal": "4101",
"name": "Revenue of Products and services Sales",
"parent_id": 41,
"transactions_sum_debit": "1658.00",
"transactions_sum_credit": "3316.00",
"children": [],
"transactions": [
{
"id": 308,
"debit": null,
"credit": "64.00",
"first_level_id": 46
},
{
"id": 310,
"debit": null,
"credit": "765.00"
},
{
"id": 318,
"debit": null,
"credit": "64.00",
"first_level_id": 46,
"invoice_id": 20
},
{
"id": 320,
"debit": null,
"credit": "765.00",
"first_level_id": 46
},
{
"id": 340,
"debit": null,
"credit": "765.00",
"first_level_id": 46
},
{
"id": 466,
"debit": "64.00",
"credit": null,
"first_level_id": 46
},
{
"id": 468,
"debit": "765.00",
"credit": null,
"first_level_id": 46
}
]
}
],
"transactions": []
},
{
"id": 15,
"Nominal": "42",
"parent_id": 4,
"transactions_sum_debit": null,
"transactions_sum_credit": null,
"children": [
{
"id": 47,
"Nominal": "4201",
"parent_id": 42,
"transactions_sum_debit": null,
"transactions_sum_credit": "1520.00",
"children": [],
"transactions": [
{
"id": 304,
"debit": null,
"credit": "380.00",
"first_level_id": 47
},
{
"id": 334,
"debit": null,
"credit": "380.00",
"first_level_id": 47
}
]
}
],
"transactions": []
}
]
}
for example in the above JSON data I want to get the sum transactions_sum_debit from all the children and show it one level up. until the parent_id = 0
My View:
//get sum of all children in json
function sumOfChildrens(parent, id) {
let data = parent;
let ids = id;
let transactions_sum_credit = 0;
//call the function recursively until the last child
for (let i = 0; i < data.length; i++) {
if (data[i].id == ids) {
transactions_sum_credit += parseFloat(data[i].transactions_sum_credit);
}
if (data[i].children) {
transactions_sum_credit += sumOfChildrens(data[i].children, ids);
}
}
console.log(transactions_sum_credit);
return transactions_sum_credit;
}
$(document).ready(function() {
$.ajax({
headers: {
"Authorization": 'Bearer ' + sessionStorage.getItem('token')
},
type: "get",
url: "{{ URL::asset('api/reports/get-generalLedger') }}",
success: function(data) {
var data = data.data;
console.log(data);
$("#tablebody").empty();
data.map(parent => {
$("#tablebody").append(
`
<tr>
<td class="${parent.Nominal} id_${parent.id}">${parent.Nominal}</td>
<td class="${parent.Nominal} id_${parent.id}">${parent.name}</td>
<td class="${parent.Nominal} id_${parent.id}"></td>
<td class="${parent.Nominal} id_${parent.id}">${sumOfChildrens(parent,parent.id)}</td>
</tr>
`);
});
},
error: function(data) {
alert(data['message']);
console.log(data['message']);
},
});
});
Stackoverflow isn't meant for other people to write code for you, but rather to answer specific questions or help solve problems. Instead of showing more code, explain what you've tried, which behavior you saw vs the one you expected.
That being said, I think the following code snippet might help you clarify your question or even solve the problem on your own.
// for each first level child
data.children.map((item) => {
// for each next level child
item.children.map((item2) => {
// this is the list of transactions
console.log(item2.transactions);
let sum = 0;
// go over each transaction
item2.transactions.map((transaction) => {
// debit != null
if (transaction.debit) {
sum += parseFloat(transaction.debit);
}
});
// here you could add the sum to the parent
console.log(sum);
});
});
Try to edit this code so it works for you and come back if you have more questions.
I am trying to access keys and arrays in my json structure with Array.map() but I'm missing something.
Here's my JSON:
{
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
I want to access payload.name, payload.brands.name(s), payloads.brands.subproducts.name(s) with Array.map() and render the values in components. How do I access nested json like using map()?
Expected output is:
Atta, Wheatola, Chakki Aata
Atta, Wheatola, Chakki Aata
Rice (Branded), Cookstar, Best Basmati
Rice (Branded), Cookstar, Extra Long Grain Basmati
You need to nest Array.map()
var data = {
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
const renderData = data.payload.map((payload) => {
return payload.brands.map(brand =>{
return brand.subProducts.map(subProduct => {
return `${payload.name}, ${brand.name}, ${subProduct.name}`
}).join("\n")
}).join("\n")
}).join("\n")
console.log(renderData);
Here might be a working example (without styling or anything):
render() {
return (
<div>
{
json.payload.map(j =>
<div>
{j.name}
{j.brands.map(b =>
<div>
{b.name}
{b.subProducts.map(s =>
<div>
{s.name}
</div>)
}
</div>
)}
</div>
)
}
</div>
);
}
You probably need to style it, or combine it with a table and columns, because it just renders the values now.
You can also use forEach since you'll have to nest map calls but you expect a flat array (?) in the end :
var json = {
"payload": [{
"id": 1,
"name": "Atta",
"brands": [{
"id": 118,
"name": "Wheatola",
"subProducts": [{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [{
"id": 25,
"name": "CookStar",
"subProducts": [{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}]
}
]
}
var result = [];
json.payload.forEach(product => {
product.brands.forEach(brand => {
brand.subProducts.forEach(subProduct => {
result.push([product.name, brand.name, subProduct.name].join(', '));
});
});
});
console.log(result);
Hi I have an array (see below for the first part of the array) and I can get the name using the code (my code is in a loop to get all names from the array)
jsonFabric.values[i].name
which gives me "3002-023"
How do I get the labels name?
which would give me "Fabric".
I have tried many variations including
jsonFabric.values[i].labels['name']
but they do not get "Fabric"
{
"totalRows": 151,
"values": [
{
"width": 1338,
"height": 2397,
"isNew": true,
"defaultScene": null,
"displayUrl": "https://example.com/designs-324/3002%20023_small.png?1=1&width=500&Cache=Default&height=500&p.dc=1&mode=max&format=jpg×tamp=636244299470877669",
"renderUrl": "https://example.com/designs-324/3002%20023.tif?1=1&width=-1&Cache=Default&p.dc=1&mode=max&format=jpg×tamp=636244299470877669",
"designOptions": {
"repeat": true,
"width": 114,
"height": 203,
"gloss": 0,
"contrast": 0,
"dropX": 0,
"dropY": 0,
"placingPointX": 0.5,
"placingPointY": 0.5,
"flip": false,
"rotation": 0
},
"id": 324,
"name": "3002-023",
"properties": [],
"propertiesPerLabel": [],
"labels": [
{
"id": 1,
"parentId": 0,
"name": "Fabric",
"path": []
}
],
"description": null,
"createDate": "2017-03-06T20:45:47.0877669",
"lastSaveDate": "2017-03-09T13:49:38.5256163",
"attachments": [],
"storageName": "3002 023.tif",
"storagePath": "designs-324/3002 023.tif",
"relations": {
"direct": []
},
"referenceId": "3002-023.tif"
},
and so on.....
{
"width": 1354,
"height": 1870,
"isNew": true,
labels represents an array. You need to access the first object of this array to print its name:
jsonFabric.values[i].labels[0].name
labels is an array, so you need to either select the first element(if there is only one) or loop through to grab the name from each.
let obj = {
"totalRows": 151,
"values": [{
"width": 1338,
"height": 2397,
"isNew": true,
"defaultScene": null,
"displayUrl": "https://example.com/designs-324/3002%20023_small.png?1=1&width=500&Cache=Default&height=500&p.dc=1&mode=max&format=jpg×tamp=636244299470877669",
"renderUrl": "https://example.com/designs-324/3002%20023.tif?1=1&width=-1&Cache=Default&p.dc=1&mode=max&format=jpg×tamp=636244299470877669",
"designOptions": {
"repeat": true,
"width": 114,
"height": 203,
"gloss": 0,
"contrast": 0,
"dropX": 0,
"dropY": 0,
"placingPointX": 0.5,
"placingPointY": 0.5,
"flip": false,
"rotation": 0
},
"id": 324,
"name": "3002-023",
"properties": [],
"propertiesPerLabel": [],
"labels": [{
"id": 1,
"parentId": 0,
"name": "Fabric",
"path": []
}],
"description": null,
"createDate": "2017-03-06T20:45:47.0877669",
"lastSaveDate": "2017-03-09T13:49:38.5256163",
"attachments": [],
"storageName": "3002 023.tif",
"storagePath": "designs-324/3002 023.tif",
"relations": {
"direct": []
},
"referenceId": "3002-023.tif"
}]
}
console.log(obj.values[0].labels[0].name)
I have 2 arrays of objects: itemsList and itemsFetched. All of the objects inside each array have the same structure (nr of key/values). One of those keys has the same 'meaning' but a different name (item_id on itemsList, id on itemsFetched ). Their values are the same.
I need to filter the itemsList array and leave only the objects that have the item_id value equal to the id value on itemsFetched. Then copy(add) the key/value count from each object on the itemsFetched array (which matches the item_id=id) to the filtered array.
I've a working code but I'm sure it isnt the best way to solve this problem. I've already asked something similar before (regarding the 'filter' part) which solved my problem, but since I had to add the 'count' part after the filtering, I ended up refactoring the whole thing.
itemsList (sample)
[
{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
},
{
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
},
{
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
},
{
"id": 401,
"name": "Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
]
itemsFetched (sample)
[
{
"item_id": 1,
"count": 50,
"unseen": true
},
{
"item_id": 401,
"count": 2,
"unseen": true
},
{
"item_id": 901,
"count": 1,
"unseen": true
}
]
resultArray (what I want in the end)
[
{
"id": 1,
"name": "Pokeball",
"count": 50,
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png",
},
{
"id": 401,
"name": "Incense",
"count": 2,
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"count": 1,
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
]
my current code (working)
let arr = [];
itemsFetched.forEach((item) => {
itemsList.forEach((item2) => {
if (item.item_id === item2.id) {
arr.push({
"id": item.item_id,
"name": item2.name,
"count": item.count,
"img": item2.img
});
}
});
});
PS: I'm able to use ES6/7 syntax/features.
You can use hash map to reduce Time complexitly, your algorithm is O(m*n), The follow is O(m+n+r)
const itemsMap = itemsList.reduce((map, item) => {
map[item.id] = item
return map
}, {})
const results = itemsFetched
.filter((item) => itemsMap.hasOwnProperty(item.item_id))
.map((item) => ({
id: item.item_id,
name: itemsMap[item.item_id].name,
count: item.count,
img: itemsMap[item.item_id].img,
}))
Use a for ... of loop (an ES6 feature) in conjunction with Array#map.
This makes it much easier to return the merged object the first time you find a match, which is a logically optimization because neither list should contain more than one entry with a given id.
const result = itemsFetched.map(data => {
for (let item of itemsList) {
if (data.item_id === item.id) {
return {
id: item.id,
name: item.name,
count: data.count,
img: item.img
}
}
}
})
Snippet:
const itemsList = [{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
}, {
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
}, {
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
}, {
"id": 401,
"name": "Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
}, {
"id": 901,
"name": "Incubator (Unlimited)",
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}]
const itemsFetched = [{
"item_id": 1,
"count": 50,
"unseen": true
}, {
"item_id": 401,
"count": 2,
"unseen": true
}, {
"item_id": 901,
"count": 1,
"unseen": true
}]
const result = itemsFetched.map(data => {
for (let item of itemsList) {
if (data.item_id === item.id) {
return {
id: item.id,
name: item.name,
count: data.count,
img: item.img
}
}
}
})
console.log(result)
One way to improve is to use for..of statement instead of forEach for the inner loop. This helps break from the loop once the id matches. There is no direct way to break from forEach method.
let arr = [];
itemsFetched.forEach((item) => {
for (let item2 of itemsList) {
if (itemsFetched.item_id === itemsList.id) {
arr.push({
"id": itemsFetched.item_id,
"name": itemsList.name,
"count": itemsFetched.count,
"img": itemsList.img
});
break;
}
}
});
Like this?
var itemsList = [
{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
},
{
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
},
{
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
},
{
"id": 401,
"name": "Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
];
var itemsFetched = [
{
"item_id": 1,
"count": 50,
"unseen": true
},
{
"item_id": 401,
"count": 2,
"unseen": true
},
{
"item_id": 901,
"count": 1,
"unseen": true
}
]
let arr = [];
itemsFetched.forEach((item) => {
itemsList.forEach((item2) => {
if (item.item_id == item2.id) {
arr.push({
"id": item.item_id,
"name": item2.name,
"count": item.count,
"img": item2.img
});
}
});
});
console.log(arr);
I have a JSON dataset which could be very large when it returns, with the following structure for each object:
{
"ctr": 57,
"averageECPC": 23,
"cost": 2732.54,
"margin": 66,
"profit": 2495.9,
"property": {
"value": "Izzby",
"uri": "/Terrago/2"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 2573.13,
"compare": 0
},
"children": [{
"ctr": 79,
"averageECPC": 54,
"cost": 3554.78,
"margin": 88,
"profit": 3145.81,
"property": {
"value": "Comvex",
"uri": "/Octocore/4"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 1247.92,
"compare": 0
}
}]
}
Now I want to search all objects in the array and return only objects which include a string of some sort, but I only want to search certain properties.
I basically have another array which contains the keys I want to search, e.g.
const iteratees = ['ctr', 'property.value', 'status.stage']
I have lodash available within the project, but I have no idea where to start.
Any ideas?
You could use filter(), some() and reduce() to do this.
const iteratees = ['ctr', 'property.value', 'status.stage'];
var searchFor = 'lo';
var result = arr.filter(function(o) {
return iteratees.some(function(e) {
var res = e.split('.').reduce(function(a, b) {
if(a) return a[b];
}, o);
if(res) {
if((res).toString().indexOf(searchFor) != -1) return true;
}
})
})
var arr = [{
"ctr": 'lorem',
"averageECPC": 23,
"cost": 2732.54,
"margin": 66,
"profit": 2495.9,
"property": {
"value": "Izzby",
"uri": "/Terrago/2"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 2573.13,
"compare": 0
},
"children": [{
"ctr": 79,
"averageECPC": 54,
"cost": 3554.78,
"margin": 88,
"profit": 3145.81,
"property": {
"value": "Comvex",
"uri": "/Octocore/4"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 1247.92,
"compare": 0
}
}]
}, {
name: 'lorem',
ctr: 12,
property: {
value: 1
},
status: {
stage: 1
}
}, {
name: 'ipsum'
}]
const iteratees = ['ctr', 'property.value', 'status.stage'];
var searchFor = 'lo';
var result = arr.filter(function(o) {
return iteratees.some(function(e) {
var res = e.split('.').reduce(function(a, b) {
if (a) return a[b];
}, o);
if (res) {
if ((res).toString().indexOf(searchFor) != -1) return true;
}
})
})
console.log(result)