Count key values from a nested object array - javascript

I have an array like this:
[
{
"costs": [{
"value": "80"
}],
"id": 4,
"name": "Subscription Fee",
"month": "March"
},
[
{
"costs": [{
"value": "200"
}],
"id": 2,
"name": "Tution",
"month": "March"
},
{
"costs": [{
"value": "10"
}],
"id": 11,
"name": "DEMO"
}
]
]
I need to have sumation of all the values from costs. How can i do that?

const data = [
{"costs":[{"value":"80"}],"id":4,"name":"Subscription Fee","month":"March"},
[
{"costs":[{"value":"200"}],"id":2,"name":"Tution","month":"March"},
{"costs":[{"value":"10"}],"id":11,"name":"DEMO"}
]
];
// flatten the arrays to get a list of objects
// iterate over this list
const res = data.flat().reduce((total, { costs = [] }) => {
// add the values of this item's costs with total
costs.forEach(({ value = 0 }) => total += +value);
return total;
}, 0);
console.log(res);

Related

how to change the format of json array by loping over

Hi I am getting data from API but I want my data in different format so that I can pass later into a function. I want to change the names of keys into a different one becasuse I have created a chart and it only draws if I send it data in certain way
This is what I am getting from API
data = {
"status": "success",
"from": "DB",
"indice": "KSE100",
"data": [
{
"stock_sector_name": "Tc",
"sector_score": "0828",
"stocks": [
{
"stock_symbol": "TRG",
"stock_score": 44
},
{
"stock_symbol": "SYS",
"stock_score": 33
}
]
},
{
"stock_sector_name": "OIL",
"sector_score": "0828",
"stocks": [
{
"stock_symbol": "FFS",
"stock_score": 44
},
{
"stock_symbol": "SMS",
"stock_score": 33
}
]
},
]
}
But I want my data to look like this like this
data = {
"name": "KSE100",
"children": [
{
"name": "A",
'points': -9,
"children": [
{
"stock_title": "A",
"value": 12,
},
{
"stock_title": "B",
"value": 4,
},
]
},
{
"name": "B",
'points': 20,
"children": [
{
"stock_title": "A",
"value": 12,
},
{
"name": "B",
"value": 4,
},
]
},
]
}
Like I want to replace
stock_sector_name = name
sector_score = value
stocks = children
stock_symbol = name
stock_score = value
I have been trying this for so much time but sill could not figured it out
function convert(d){
return {
name : d.indice,
children : d.data.map(y=>{
return {
name : y.stock_sector_name,
points : y.sector_score,
children : y.stocks.map(z=>{
return {
stock_title: z.stock_symbol,
value : z.stock_score
}
})
}
})
}
}
You can do something like this
const data = {
"status": "success",
"from": "DB",
"indice": "KSE100",
"data": [{
"stock_sector_name": "Tc",
"sector_score": "0828",
"stocks": [{
"stock_symbol": "TRG",
"stock_score": 44
},
{
"stock_symbol": "SYS",
"stock_score": 33
}
]
},
{
"stock_sector_name": "OIL",
"sector_score": "0828",
"stocks": [{
"stock_symbol": "FFS",
"stock_score": 44
},
{
"stock_symbol": "SMS",
"stock_score": 33
}
]
},
]
}
const data2 = {
"name": "KSE100",
"children": [{
"name": "A",
'points': -9,
"children": [{
"stock_title": "A",
"value": 12,
},
{
"stock_title": "B",
"value": 4,
},
]
},
{
"name": "B",
'points': 20,
"children": [{
"stock_title": "A",
"value": 12,
},
{
"name": "B",
"value": 4,
},
]
},
]
}
//stock_sector_name = name
//sector_score = value
//stocks = children
//stock_symbol = stock_title
//stock_score = value
const keys = {
stock_sector_name: "name",
sector_score: "points",
stocks: "children",
stock_symbol: "stock_title",
stock_score: "value",
indice: "name",
//data: "children"
}
const rename = (value) => {
if (!value || typeof value !== 'object') return value;
if (Array.isArray(value)) return value.map(rename);
return Object.fromEntries(Object
.entries(value)
.map(([k, v]) => [keys[k] || k, rename(v)])
);
}
renamedObj = rename(data);
console.log(renamedObj);

find if an array is inside another nested array

I 'm trying to find if array1 is is inside the nested array2.data.
const array1 = [
{
name: "Color",
value: "Yellow",
},
{
name: "Size",
value: "Small",
},
];
const array2 = [
{
"id": 1,
"data": [
{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Small"
}
]
},
{
"id": 2,
"data": [
{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Medium"
}
]
},
{
"id": 3,
"data": [
{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Large"
}
]
},]
this is what I have tread but not giving me the result I need :
array2.map(( a ) => {
a.data.map(( data ) => {
array1.map((option) => {
if( data === option) {
return data;
}
});
});
});
JSON.stringify() the needle array (array1) and the data attribute of each array member in array2 and compare the two; if they match, array1 is present in array2:
const array1 = [{
name: "Color",
value: "Yellow",
},
{
name: "Size",
value: "Small",
},
];
const array2 = [{
"id": 1,
"data": [{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Small"
}
]
},
{
"id": 2,
"data": [{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Medium"
}
]
},
{
"id": 3,
"data": [{
"name": "Color",
"value": "Yellow"
},
{
"name": "Size",
"value": "Large"
}
]
},
];
const dataArrayIsPresentInArray2 = needle => !!array2.find(cv => JSON.stringify(cv.data) === JSON.stringify(needle));
console.log(dataArrayIsPresentInArray2(array1)); // true
As mentioned in the comments, this method will only work for data structures serializable with JSON.stringify().
If the order of the objects in array1 does not matter, you can iterate through every item and use Array.every to check whether each item in the data property after stringification is equal to an item in array1 after stringification.
const array1=[{name:"Color",value:"Yellow"},{name:"Size",value:"Small"}],array2=[{id:1,data:[{name:"Color",value:"Yellow"},{name:"Size",value:"Small"}]},{id:2,data:[{name:"Color",value:"Yellow"},{name:"Size",value:"Medium"}]},{id:3,data:[{name:"Color",value:"Yellow"},{name:"Size",value:"Large"}]}];
const contains = array2.some(e => e.data.every(f => array1.some(g => JSON.stringify(g) == JSON.stringify(f))));
console.log(contains)
if you wanna just to check if arr1 in arr2.date
i would probably just
loop over arr2.data and compare each iteration to arr1 and if it is the same return or change some value to know the output .
something like :
// var that represent if arr1 inside arr2.data
let arr1InsideArr2= false
for (let i of array2){
if (i.data == array1){
return arr1InsideArr2= true
}
}
and then do with the var arr1InsideArr2 whatever you want to check .

Copy second nested array of objects into first nested array of objects

How can I assign key value from array of object to another array object
I would like to assign the key:value pair to the existing array of object from the another array of objects.
I have check this thread but it is not working in my case.
I have tried something like this but that is not returning the desired output that I am looking for.
const DataA = {
"id": 57,
"status": true,
"options": [{ "id": 1, "name": "Type A" },
{ "id": 2, "name": "Type B" },
{ "id": 3, "name": "Type C" }]
}
const DataB = {
"id": 57,
"status": true,
"options": [{ "id": 1, "value": 10 },
{ "id": 2, "value": 20 },
{ "id": 3, "value": 30 }]
}
let result;
var A1 = DataA.options.map((v) => {
console.log(v);
result = v;
})
var A2 = DataB.options.map(v => {
result.options = v;
console.log("result",result);
})
let arr3 = DataA.options.map((item, i) => Object.assign({}, item, DataB[i]));
console.log(arr3);
Result will be I need as below:
const DataA = {
"id": 57,
"status": true,
"options": [{ "id": 1, "name": "Type A", "value": 10 },
{ "id": 2, "name": "Type B", "value": 20 },
{ "id": 3, "name": "Type C", "value": 30 }]
}
I need to merge the deep clone of the array that is slightly different from this thread.
The linked duplicate does actually address your question, but you need to adjust it to your situation and not just copy paste.
DataA.options = DataA.options.map((item, i) => Object.assign({}, item, DataB.options[i]));
but since this mutates the original DataA object anyway, you may as well just use forEach() and avoid creating the intermediate array from .map().
DataA.options.forEach((item, i) => Object.assign(item, DataB.options[i]));
Both of the above assume that the options arrays of both objects are a. of the same length, and b. sorted by id. To avoid these assumptions you can use .find() to look for matching elements instead of relying on index.
DataA.options.forEach(item =>
Object.assign(item, DataB.options.find(({ id }) => id === item.id)));
const DataA = {
"id": 57,
"status": true,
"options": [
{ "id": 1, "name": "Type A" },
{ "id": 2, "name": "Type B" },
{ "id": 3, "name": "Type C" }]
}
const DataB = {
"id": 57,
"status": true,
"options": [
{ "id": 1, "value": 10 },
{ "id": 2, "value": 20 },
{ "id": 3, "value": 30 }]
}
DataA.options.forEach(item =>
Object.assign(item, DataB.options.find(({ id }) => id === item.id)));
console.log(DataA)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Look up values in an array using looping forEach Google Apps Script Javascript

I have an object that looks like the following {key: id numbers}
var obj = {
"c4ecb": {id: [3]},
"a4269": {id: [34,36]},
"d76fa": {id: [54,55,60,61]},
"58cb5": {id: [67]}
}
How do I loop each above id in the following array, and return the label?
var response =
{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}
Finally, what I want to do is look up the key and return a string of id values.
For example, input c4ecb and output strawberry. Input a4269 and output lettuce, radish. Input d76fa and output "spaghetti, rigatoni, lasagna, fettuccine"
I think to join the multiple labels output into one string I could use something like
array.data.vegetables.map(vegetables => vegetables.value).join(', ')].toString();
So in the end I want to have something like
var fruits = [some code that outputs "strawberry"];
var vegetables = [some code that outputs "lettuce, radish"];
var pasta = [some code that outputs "spaghetti, rigatoni, lasagna, fettuccine"];
What I've tried so far:
The following loop will return the id only if there is one id to be called for: e.g. only in case one where {id: 3} but returns null in cases like {id: 34,36} (because it's looking for '34,36' in id, which doesn't exist - I need to look for each one individually.
response.data.forEach(({key, options}) => {
if (obj[key]) {
options.forEach(({id, label}) => {
if (id == obj[key].id) obj[key].label = label;
});
}
});
console.log(obj)
Filter the response object to focus on the category that matches the id.
Map over the options array and select the items which appear in obj[id].
Finally convert the filtered results to a string.
See filteredLabelsAsString() function below for implementation.
var obj = {
"c4ecb": {"id": [3]},
"a4269": {"id": [34,36]},
"d76fa": {"id": [54,55,60,61]},
"58cb5": {"id": [67]}
}
var response =
[{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}];
function filteredLabelsAsString(obj_key, obj, content=response) {
// sanity check: obj must contain obj_key
if (Object.keys(obj).includes(obj_key)) {
return content.filter((item) => {
// filter content using value of obj_key
return item.data[0].key == obj_key;
}).map((item) => {
// item : { success: true, data: [] }
// map over options array
return item.data[0].options.map((opt) => {
// option : {id, label}
// return the label if the id is in the obj object's list
if (obj[item.data[0].key].id.includes(opt.id))
return opt.label;
}).filter((label) => {
// filter out empty items
return label !== undefined;
});
}).join(",");
}
// if obj does not contain obj_key return empty string
return "";
}
console.log("fruits: " + filteredLabelsAsString("c4ecb", obj));
console.log("vegetables: " + filteredLabelsAsString("a4269", obj));
console.log("pasta: " + filteredLabelsAsString("d76fa", obj));

Transform structure of array of objects

I have data like -
var data = [{"DefaultZone":[{"key":"stream0","value":100},
{"key":"stream1","value":50},
{"key":"stream2","value":10}
]},
{"Zone 1":[{"key":"stream0","value":120},
{"key":"stream1","value":55},
{"key":"stream2","value":15}
]}
]
and wanted to transform it like -
var data = [{"key": "stream0", "values":[{"x":"DefaultZone","y":100}, {"x":"Zone 1","y":120}]},
{"key": "stream1", "values":[{"x":"DefaultZone","y":50}, {"x":"Zone 1","y":55}]},
{"key": "stream2", "values":[{"x":"DefaultZone","y":10}, {"x":"Zone 1","y":15}]}
];
using JavaScript(ES6). Any help would be highly appreciated..
Here is the first way that came to mind:
var data = [{
"DefaultZone": [
{ "key": "stream0", "value": 100 },
{ "key": "stream1", "value": 50 },
{ "key": "stream2", "value": 10 }]
}, {
"Zone 1": [
{ "key": "stream0", "value": 120 },
{ "key": "stream1", "value": 55 },
{ "key": "stream2", "value": 15 }]
}];
let working = data.reduce((p, c) => {
let x = Object.keys(c)[0];
c[x].forEach(v => {
if (!p[v.key]) p[v.key] = [];
p[v.key].push({ x: x, y: v.value });
});
return p;
}, {});
let output = Object.keys(working).map(v => ({ key: v, values: working[v] }));
console.log(output);
Further reading:
the array .reduce() method
the Object.keys() method
the array .forEach() method
the array .map() method
Although I like nnnnnn's answer, here is another one, using only the Object.keys() method:
var data = [{
"DefaultZone": [{
"key": "stream0",
"value": 100
}, {
"key": "stream1",
"value": 50
}, {
"key": "stream2",
"value": 10
}]
}, {
"Zone 1": [{
"key": "stream0",
"value": 120
}, {
"key": "stream1",
"value": 55
}, {
"key": "stream2",
"value": 15
}]
}]
final = {}
data.forEach(function(x) {
Object.keys(x).forEach(function(y) {
x[y].forEach(function(z) {
if (!final[z['key']]) final[z['key']] = [];
final[z['key']].push({
'x': y,
'y': z['value']
})
})
})
})
answer = []
Object.keys(final).forEach(function(x) {
answer.push({
'key': x,
values: final[x]
})
})
console.log(answer)

Categories