Change the positive number to negative number in array of object - javascript

Given array of object in database:
detail : [
0: {
Code: "Code 1",
Price: "1.00",
IncTaxPrice: "1.20",
Tax:"0.20",
},
1: {
Code: "Code 2",
Price: "9.00",
IncTaxPrice: "9.20",
Tax:"0.20",
}
]
Output i want with key and value negative (for eg)
[
{
Code: "Code 1",
Price: "-1.00",
IncTaxPrice: "-1.20",
Tax: "-0.20",
},
{
Code: "Code 2",
Price: "-9.00",
IncTaxPrice: "-9.20",
Tax: "-0.20",
},
];
I tried with the map, filter function but it gave an error I guess I am missing something.
After it filters properly I will use -Math.abs(), to convert positive to negative.
let final = detail.map(a => Object.values(a).filter(v => typeof v === 'number'))
the element like price,tax are something like 8 different elements of numbers and amounts.

Thanks for #VLAZ suggestion in the comment. I think you can filter by the key using Object.keys().
Example below:
const detail = [
{
Code: "Code 1",
Price: "1.00",
IncTaxPrice: "1.20",
Tax: "0.20",
},
{
Code: "Code 2",
Price: "9.00",
IncTaxPrice: "9.20",
Tax: "-0.20",
},
];
let final = detail.map(x => ({
Code: x.Code,
Price: -Number(x.Price),
IncTaxPrice: -Number(x.IncTaxPrice),
Tax: -Number(x.Tax),
}));
console.log(final);

You should wrap your 0, 1 indexes in curly brackets as it is an array of objects. You can't just define it as you did because indexes 0 and 1 are not just numbers (fex. [0,1,2] is valid but not [0:{code:...},1:{code:...}] They are contining an object inside, so they are objects and you can't map if your array of objects is not properly defined as:
[{0:{code:..}},{1:{code:..}}.
Also using typeof filter wont' work because all values are type string.
I would go like this:
let detail = [ {
0: {
Code: "Code 1",
Price: "1.00",
IncTaxPrice: "1.20",
Tax:"0.20",
}},
{1: {
Code: "Code 2",
Price: "9.00",
IncTaxPrice: "9.20",
Tax:"0.20",
}}
]
detail.map(el=>{
el[Object.keys(el)[0]]['Price']=(-parseFloat(el[Object.keys(el)[0]]['Price'])).toString()
el[Object.keys(el)[0]]['IncTaxPrice']=(-parseFloat(el[Object.keys(el)[0]]['IncTaxPrice'])).toString()
el[Object.keys(el)[0]]['Tax']=(-parseFloat(el[Object.keys(el)[0]]['Tax'])).toString()
return
}
)

Related

Returning the ids from the object within the arrays

I have a multidimensional javascript array of objects that I am trying to use to simply collate the Unit id into a new array as shown below.
What is the best solution for returning the id within the inner value so I just get an array of the ids whatever I try seems to not work
[
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
]
Expected output - just return an array with simply the ids
e.g
ids = [ 10000282, 10000340, 10000341, 10000334 ]
Assuming that data is in variable data:
> data.map(o => o.units.map(u => u.id)).flat()
[ 10000282, 10000340, 10000341, 10000334 ]
This assumes you're in an environment where .flat() is a thing.
If that's not the case, the longer way around is
const ids = [];
data.forEach(o => {
o.units.forEach(u => {
ids.push(u.id);
});
});

how to count value in object javascript

hay , i have JSON format like this from looping
let data = {
status: "0"
description: "item 1"
}
{
status: "1"
description: "item 1"
}
i want to get value status and count how many status with value 0
expected output like this :
let gg = "status 0 as much 1"
how to do this in javascript ? thanks
First your JSON is invalid. Possibly what you want is an array that contains objects that you can iterate over. You need to quote your data properly, and include commas where they're required.
'[{ "status": "0", "description": "item 1" }, { "status": "1", "description": "item 1" } ]'
Once you have valid JSON and you've parsed it you can iterate over the objects.
Here's a function that passes in the parsed data, and the desired property and value as arguments. It filters out the objects that match the condition, and returns a string with the details.
const data = [{ status: '0', description: 'item 1' }, { status: '1', description: 'item 1' }, { status: '0', description: 'item 1' } ];
function getStatus(data, type, value) {
// `filter` out the objects where the property key matches the value
const out = data.filter(obj => obj[type] === value);
// Return a template string with the details
return `status ${value} as much ${out.length}`;
}
console.log(getStatus(data, 'status', '0'));
You missed some commas but I think you want something like
Edited
If you are trying to extract this from an object with property keys you should use..
Object.values(obj).reduce((acc, cur) => !cur.status ? acc + 1 : acc, 0)
If it's an array
arr.reduce((acc, cur) => !cur.status ? acc + 1 : acc, 0)
Like others have said the object in the question is not valid

Nested arrays with objects, lodash meanBy

Can someone please help me understand how to make this work. Everytime I feel like I start to understand arrays and objects in Javascript it turns out that I still don't.
I'm trying to get the average of all prices in the following datastructure by using lodash meanBy
[
{
date: "2019-12-17",
items: [
{ id: "1", state: "accepted", price: "90.5" },
{ id: "2", state: "rejected", price: "20.0" },
{ id: "3", state: "open", price: "10.5" },
]
},
{
date: "2019-12-18",
items: [
{ id: "4", state: "open", price: "450.0" },
{ id: "5", state: "rejected", price: "40.1" },
{ id: "6", state: "accepted", price: "50.9" },
]
}
]
If you provide the answer, can you also please try to explain how you select something nested in items, because that's as far as I get before I get lost.
In this case instead of selecting nested values, it's easier to flatten the items to a single array, and then apply _.meanBy(). In addition, the prices are strings, and not numbers, so you'll need to convert them.
Flatten the items to a single array with Array.flatMap(), and then use _.meanBy(), and get the numeric values of the prices:
const data = [{"date":"2019-12-17","items":[{"id":"1","state":"accepted","price":"90.5"},{"id":"2","state":"rejected","price":"20.0"},{"id":"3","state":"open","price":"10.5"}]},{"date":"2019-12-18","items":[{"id":"4","state":"open","price":"450.0"},{"id":"5","state":"rejected","price":"40.1"},{"id":"6","state":"accepted","price":"50.9"}]}]
const result = _.meanBy(_.flatMap(data, 'items'), o => +o.price)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Another approach is to get the general average, by getting the average of each items array separately , and then getting the average of all averages.
const data = [{"date":"2019-12-17","items":[{"id":"1","state":"accepted","price":"90.5"},{"id":"2","state":"rejected","price":"20.0"},{"id":"3","state":"open","price":"10.5"}]},{"date":"2019-12-18","items":[{"id":"4","state":"open","price":"450.0"},{"id":"5","state":"rejected","price":"40.1"},{"id":"6","state":"accepted","price":"50.9"}]}]
const result = _.meanBy(data, ({ items }) => _.meanBy(items, o => +o.price))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

How to get highest difference between two numbers in a JSON object

I'm working with NodeJS to create a "Featured Product" widget on a website. I have a JSON object with SKU, price, and sale_price. What's the best way to get the SKU of the item that has the highest discount (Difference between price and sale_price)?
I tried doing it by for looping through the items and find the difference between price and sale_price, push the results to an array then get the max, but I cannot get the SKU at that point.
Example of the JSON object that I have:
{ "item_number":12341231, "price":"250", "sale_price":"219.99"},
{ "item_number":12341232, "price":"210", "sale_price":"209.99"},
{ "item_number":12341233, "price":"20", "sale_price":"12.99"},
{ "item_number":12341234, "price":"150", "sale_price":"19.99"},
{ "item_number":12341235, "price":"60", "sale_price":"29.99"},
{ "item_number":12341236, "price":"10", "sale_price":"5.99"}
];
For example the program would return 1231234 as the SKU of the featured item, because the discount is ~$130.
I just want a quick solution, don't worry about performance.
You could reduce the array with a single loop and take the one with the greatest delta.
var array = [{ item_number: 12341231, price: "250", sale_price: "219.99" }, { item_number: 12341232, price: "210", sale_price: "209.99" }, { item_number: 12341233, price: "20", sale_price: "12.99" }, { item_number: 12341234, price: "150", sale_price: "19.99" }, { item_number: 12341235, price: "60", sale_price: "29.99" }, { item_number: 12341236, price: "10", sale_price: "5.99" }],
result = array.reduce((a, b) =>
a.price - a.sale_price > b.price - b.sale_price ? a : b);
console.log(result);
If performance is not an issue, you can sort your products in descending order and get the first one from the sorted result:
const data = [
{ "item_number":12341231, "price":"250", "sale_price":"219.99"},
{ "item_number":12341232, "price":"210", "sale_price":"209.99"},
{ "item_number":12341233, "price":"20", "sale_price":"12.99"},
{ "item_number":12341234, "price":"150", "sale_price":"19.99"},
{ "item_number":12341235, "price":"60", "sale_price":"29.99"},
{ "item_number":12341236, "price":"10", "sale_price":"5.99"}
];
const maxDiffProduct = data.sort((a, b) => (b.price - b.sale_price) - (a.price - a.sale_price))[0];
console.log(maxDiffProduct.item_number);

Search through an array of objects looking for non empty objects JS

At the core of the problem I have:
[
{amount: 0, name: "", icon: "", description: ""} // default object added to array
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
I want to know how to use lodash find such that, as long as any key has a value other then 0 or "" we are not considered "empty".
So in this case lodash find would return:
[
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
Or it would return undefined.
What I have is:
lodashFind(theArray, function(obj){
// Now what? How do I go through the objects?
});
I am not sure how to go through objects saying, as long as there is no 0 for amount and no string has "" then return that object.
Ideas?
Use _.filter, _.some, _.all or _.negate of lodash to achieve this:
var data = [
{ name:'a', age:0 },
{ name:'b', age:1 },
{ name:'', age:0 }
];
// lists not empty objects (with at least not empty field)
console.log(_.filter(data, _.some));
// outputs [{name:'a',age:0},{name:'b',age:1}]
// lists 'full' objects (with no empty fields)
console.log(_.filter(data, _.all));
// outputs [{name:'b',age:1}]
// lists 'empty' objects (with only empty fields)
console.log(_.filter(data, _.negate(_.some)));
// outputs [{name:'',age:0}]
_.some and _.all search for truthy values, '' and 0 is not truthy. Namely, the following JavaScript values are falsy: false, 0, '', null, undefined, NaN. Every other value is truthy.
Using just regular javascript, this is quite easy as well, just filter the array based on the objects values etc, like this
var arr = [
{amount: 0, name: "", icon: "", description: ""},
{amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]
arr = arr.filter(function(o) {
return Object.keys(o).filter(function(key) {
return o[key] != 0 && o[key].toString().trim().length > 0;
}).length > 0;
});
FIDDLE

Categories

Resources