Add columns value in react.js - javascript

What is the best approach to add all the columns value?
json
[
{
"id": "men",
"label": "men",
"value": 3,
"color": "#468df3"
},
{
"id": "women",
"label": "women",
"value": 5,
"color": "#ba72ff"
},
{
"id": "children",
"label": "children",
"value": 5,
"color": "#a1cfff"
}
]
I am fetching data from the server I like to add all the values and display it in the console.
For example const value = 3+5+5 = 13 in console.

That's not related to reactjs, simply
let raw = '[{"id": "men","label": "men","value": 3,"color": "#468df3"},{"id": "women","label": "women","value": 5,"color": "#ba72ff"},{"id": "children","label": "children","value": 5,"color": "#a1cfff"}]';
let data = JSON.parse(raw);
let sum_value = data.reduce((sum, current)=>{
return sum + current.value
}, 0);
console.log(sum_value);

Related

Is there any way to filter objects from array of objects that should include all selected values in javascript

Here i have skills array and employees array and i am trying to get the employees that includes all the skills that are included in skills array using reduce, filter or find method. I am trying to stored the filtered employees in filteredItems but got stuck in it.
filteredItems = Skills?.length>0 ?
Employees?.filter((item) => {
return item.Skills.find((ele) => {
return Skills.find((el) => {
if(el.value === ele.id){
return ele
}
})
})
}) : []
Below are the arrays mentioned.
Skills Array
[
{
"value": 6,
"label": "Marketing"
},
{
"value": 20,
"label": "Golang"
}
]
Employees Array
[
{
"name": "Hassan",
"id": 56,
"Skills": [
{
"id": 20,
"name": "Golang",
},
],
},
{
"name": "Haroon",
"id": 95,
"Skills": [
{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
},
]
For example, in above scenario of arrays it should return employee of id of 95 not return employee of id 56 because it includes skills but not all that are mention in skills array.
I found it easier to first encapsulate an array of skill IDs to search for.
let skillIds = Skills.map(s => s.value);
Then I filtered and compared the end result to the length of the skill Ids array:
let filteredItems = Skills?.length > 0 ?
Employees?.filter(item => item.Skills.filter( s =>
skillIds.includes(s.id)).length==skillIds.length): []
let Skills = [{
"value": 6,
"label": "Marketing"
}, {
"value": 20,
"label": "Golang"
}]
let Employees = [{
"name": "Hassan",
"id": 56,
"Skills": [{
"id": 20,
"name": "Golang",
}],
}, {
"name": "Haroon",
"id": 95,
"Skills": [{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
}, ]
let skillIds = Skills.map(s => s.value);
let filteredItems = Skills?.length > 0 ?
Employees?.filter(item => item.Skills.filter( s => skillIds.includes(s.id)).length==skillIds.length): []
console.log(filteredItems)
You could create another property in the employees array.. call it "QUalified". Default it to true, then set it to false when the employee doesn't have a skill in the skills array.
let arSkills = [
{
"value": 6,
"label": "Marketing"
},
{
"value": 20,
"label": "Golang"
}
];
let arEmp = [
{
"name": "Hassan",
"id": 56,
"Skills": [
{
"id": 20,
"name": "Golang",
},
],
},
{
"name": "Haroon",
"id": 95,
"Skills": [
{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
},
];
arEmp.forEach(ele =>{
ele.Qualified = true;
let arTmp = [];
for(let {id} of ele.Skills)
arTmp.push(id)
for(let {value} of arSkills)
if(!arTmp.includes(value))
ele.Qualified = false
});
let arQual = arEmp.filter((ele) =>{
return ele.Qualified
});
console.log(arQual);

Javascript get data from within brackets

I understand that I can extract for example the currency ("EUR") with order.unitPricePaid.currency, but how do I extract for example the tax number ("GB08713331")?
Below is the data I have:
{
"unitPricePaid": {
"currency": "EUR",
"value": "59.00"
},
"formSubmission": [
{
"label": "User",
"value": "Creatively"
}, {
"label": "Tax number",
"value": "GB08713331"
}
]
}
order.formSubmission[1].value
What this does is it looks at the "formSubmission" as an array. So, you can access each element how it is. Since "label: Tax Number" and "value: GB08713331" are in the second element of the array, you use "formSubmission[1]"
You can get the tax number using Array.prototype.find on the formSubmission property.
const data = {
"unitPricePaid": {
"currency": "EUR",
"value": "59.00"
},
"formSubmission": [{
"label": "User",
"value": "Creatively"
}, {
"label": "Tax number",
"value": "GB08713331"
}]
};
const taxNumber = data.formSubmission
.find(field => field.label === 'Tax number').value;
console.log(`Tax number = "${taxNumber}"`);
Assuming this object:
var order = { "unitPricePaid": { "currency": "EUR", "value": "59.00" }, "formSubmission": [{ "label": "User", "value": "Creatively" }, { "label": "Tax number", "value": "GB08713331" }] }
the path to that value would be order.formSubmission[1].value. The [1] means we are accessing the element at index 1 of the array (index 0 would be the first element).

Search array of objects for a specific key provided from another array

I have an object with the structure of:
[
{
"id": "NONSTOPS",
"label": "Nonstop",
"value": "no"
},
{
"id": "REWARDS",
"label": "Rewards",
"value": "no"
},
{
"id": "SEAT",
"label": "Seats",
"value": "no"
},
{
"id": "BAGS",
"label": "Bags",
"value": "no"
}
]
and an array with a structure of
["NONSTOPS", "REWARDS"]
To return
[
{
"id": "NONSTOPS",
"label": "Nonstop",
"value": "yes"
},
{
"id": "REWARDS",
"label": "Rewards",
"value": "yes"
},
{
"id": "SEAT",
"label": "Seats",
"value": "no"
},
{
"id": "BAGS",
"label": "Bags",
"value": "no"
}
]
Based on the array, it would search the object and change the value to "yes" if there exists an ID on the array.
Here's my code so far
for(let i=0; i< obj.length; i++){
for(let j = 0; j<array.length; j++){
if(obj[i].id === array[j]){
obj[i].value ='yes'
}
}
}
Something seems off about my code and I was wondering if there was an easier way to do this, maybe with a mapper of some sorts?
Can probably use a .forEach and an indexOf check on your array (just to be more concise, there's nothing wrong with your approach)
obj.forEach(o => {
if (array.indexOf(o.id) > -1) o.value = "yes";
});
You can use includes
const data = [{
"id": "NONSTOPS",
"label": "Nonstop",
"value": "no"
},
{
"id": "REWARDS",
"label": "Rewards",
"value": "no"
},
{
"id": "SEAT",
"label": "Seats",
"value": "no"
},
{
"id": "BAGS",
"label": "Bags",
"value": "no"
}
]
const lookup = ["NONSTOPS", "REWARDS"];
const reduced = data.map(d => {
return {id: d.id, label: d.label, value: lookup.includes(d.id) ? "YES" : "NO"}
});
console.log(reduced);
You can use a simple for of loop to iterate over the array of objects and then check with the built in includes function if the value exist in the flat array.
const arr = [
{
"id": "NONSTOPS",
"label": "Nonstop",
"value": "no"
},
{
"id": "REWARDS",
"label": "Rewards",
"value": "no"
},
{
"id": "SEAT",
"label": "Seats",
"value": "no"
},
{
"id": "BAGS",
"label": "Bags",
"value": "no"
}
]
const arrToCompare = ["NONSTOPS", "REWARDS"]
for (let obj of arr) {
// you can use includes to find is the value exist in the arrToCompare
if (arrToCompare.includes(obj.id)) {
// if exists then mutate it
obj.value = 'yes';
}
}
console.log(JSON.stringify(arr, null, 4));
In the question you have mentioned that you want to return the valid elements. You can use filter() for the same.
var result = obj.filter(o => (array.indexOf(o.id) > -1) );

Re-arrage JSON values from existing values

The JSON provided is kind of unstructured and doesn't meet many of my
requirements. I have tried this many ways but does take a very long time
when I provide 100,000 records
Implemented Code
for (var f in stack.data) {
var field = new Object();
for (var o in stack.data[f]['field_values']) {
field[stack.data[f]['field_values'][o]['field_name']] = stack.data[f]['field_values'][o]['value'];
}
stack.data[f]['field_values'] = field;
}
console.log(JSON.stringify(stack, null, 2));
Input JSON:
var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}
Expected Output:
{
"data": [
{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": {
"Newsletter?": true,
"Parent": "Gigi Hallow",
"Birthday": "2018-04-29",
"Related": "2012-00121-Sass",
"Referral": "Don Ho",
"Spouse": "Wo Fat"
}
Sometimes "field_values can be empty. Need to check them as well
{
"id": 950821118875,
"name": "www.google.com",
"field_values": [],
}
This is mostly re-arranging the values. Here values becomes keys. There should actually be one liner to handle this, but i am run out of options.
Hope the question is clear
It would probably help to declare a variable to hold the array element, rather than doing 4 levels of indexing every time through the loop. You can also use destructuring to extract the properties of the object.
And use {} rather than new Object.
Even if this doesn't improve performance, it makes the code easier to read.
var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}
for (var f in stack.data) {
const field = {};
const fobj = stack.data[f];
for (var o in fobj.field_values) {
const {field_name, value} = fobj.field_values[o];
field[field_name] = value;
}
fobj.field_values = field;
}
console.log(JSON.stringify(stack, null, 2));

Create new array with deleted values (React Native)

I have an array like this one :
[
Object {
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
Object {
"hex": "#50690e",
"label": "text",
"value": "354",
},
Object {
"hex": "#925fa3",
"label": "text",
"value": "355"
}]
I have another array with this :
Array [
"355",
"356"
]
I'm looking to create a the first array but without the objects containing value 355 and 356. I tried with .filter()... but I'm a newbie with JS & React Native :-)
I tried some stuffs but almost every time I recreate my Array only with the values (i'm losing the objects inside)...
What I want to do is :
If I found 355 and 356 in my First Array, I delete the objects with them and I recreate my array with the only object remaining (value 364)
I was thinking about sth like that :
myFirstArray.filter(item => item.value != mySecondArray.value) but it's not a success ...
Thanks for help
The previous answers involve iterating over your id's array many times.
A more performant solution would be to store the id's in a set and then use that combined with a filter to produce your new array.
const arr = [
{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
...,
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}];
const ids = ["354", "355"];
const idSet = new Set(ids);
const output = arr.filter(e => !idSet.has(e.value));
var firstArray = [{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
{
"hex": "#50690e",
"label": "text",
"value": "354",
},
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}]
var secondArray = [
"355",
"356"
]
var thirdArray = firstArray.filter(item => secondArray.includes(item.value))
console.log(thirdArray)
You are nearly there, just use Array#includes() to determine whether or not the value of an item is in the second array:
myFirstArray.filter(item => !mySecondArray.includes(item.value))
let myFirstArray = [{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
{
"hex": "#50690e",
"label": "text",
"value": "354",
},
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}
]
let mySecondArray = [
"355",
"356"
]
console.log(
myFirstArray.filter(item => !mySecondArray.includes(item.value))
)

Categories

Resources