Javascript get data from within brackets - javascript

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).

Related

filter nested array with Javascript

having an array with objects and inside an options array how do I filter the inner array of objects by key value?
Here is the following example:
let test = [{
"options": [{
"label": "Audi",
"value": 10
},
{
"label": "BMW",
"value": 18
},
{
"label": "Mercedes Benz",
"value": 116
},
{
"label": "VW",
"value": 184
}
],
"label": "test1"
},
{
"options": [{
"label": "Adler",
"value": 3664
},
{
"label": "Alfa Romeo",
"value": 3
},
{
"label": "Alpine",
"value": 4
}
],
"label": "test2"
}
]
how do I get back the object:
{
"label": "Audi",
"value": 10
}
if I filter with keyword Audi
return label.toLowerCase().includes(inputValue.toLowerCase());
I tried with the following
test.map((k) => {
res = k.options.filter((j) => {
inputValue.toLowerCase();
if (j.label.toLowerCase().includes(inputValue.toLowerCase())) {
return j;
}
});
});
You need to return the result of filter(), not just assign it to a variable, so that map() will return the results.
let test = [{
"options": [{
"label": "Audi",
"value": 10
},
{
"label": "BMW",
"value": 18
},
{
"label": "Mercedes Benz",
"value": 116
},
{
"label": "VW",
"value": 184
}
],
"label": "test1"
},
{
"options": [{
"label": "Adler",
"value": 3664
},
{
"label": "Alfa Romeo",
"value": 3
},
{
"label": "Alpine",
"value": 4
}
],
"label": "test2"
}
]
let inputValue = "audi";
let search = inputValue.toLowerCase();
let result = test.map(k => k.options.filter(j => j.label.toLowerCase().includes(search)));
console.log(result);
This will return all options matching the search query :
function find(array, query) {
return array.reduce((prev, current) => prev.concat(current.options), []).filter(item => item.label.includes(query))
}
find(test, 'Audi')
Use flatMap() followed by filter():
let test=[{options:[{label:"Audi",value:10},{label:"BMW",value:18},{label:"Mercedes Benz",value:116},{label:"VW",value:184}],label:"test1"},{options:[{label:"Adler",value:3664},{label:"Alfa Romeo",value:3},{label:"Alpine",value:4}],label:"test2"}]
let result = test.flatMap(el => {
return el.options.filter(car => car.label == "Audi")
})[0]
console.log(result)
You need to go two levels deep when traversing your array.
function filterArray(needle, haystack) {
return haystack
.map(h => h.options)
.flatMap(h => h )
.filter(h => h.label.toLowerCase().includes(needle.toLowerCase()));
CodeSandbox
This might gile your answer:
console.log(test[0].options[0]);

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));

Add columns value in react.js

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);

Comparing arrays of objects and remove duplicate [duplicate]

This question already has answers here:
Remove duplicates in an object array Javascript
(10 answers)
Closed 5 years ago.
I have an array containing arrays of objects which I need to compare.
I've looked through multiple similar threads, but I couldn't find a proper one that compares multiple arrays of objects (most are comparing two arrays of objects or just comparing the objects within a single array)
This is the data (below is a JSFiddle with code sample)
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
I want to remove all duplicate arrays of objects, regardless of the length of data (there could be a lot more records).
I managed to get the unique ones extracted into an object:
const unique = data.reduce(function(result, obj) {
return Object.assign(result, obj)
}, [])
That doesn't work for me though, because I need 1 of the duplicated arrays to remain and the returned data to be an array as well, instead of an object. E.g.:
// result I need
[
[
{
"id":"65",
"name":"Some object name",
"value":90
},
{
"id":"89",
"name":"Second Item",
"value":20
}
],
[
{
"id":"14",
"name":"Third one",
"value":10
}
]
]
So how do I compare each array of objects to the others in the parent array and preserve one of each duplicated or unique array of objects?
JSFiddle
you can achieve so by using function.As below. Not sure about best optimum way of doing so.
var testArray = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
function removeDuplicatesFromArray(arr){
var obj={};
var uniqueArr=[];
for(var i=0;i<arr.length;i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = arr[i];
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
];
const temp = {};
const result = [];
data.forEach(itemArr => {
const items = itemArr.filter(item => {
const isUnique = temp[`${item.id}-${item.name}-${item.value}`] === undefined;
temp[`${item.id}-${item.name}-${item.value}`] = true;
return isUnique;
});
if (items.length !== 0)
result.push(items);
});
console.log(result);

Categories

Resources