I'm having some trouble formatting/transforming some simple data into a format that I can use to graph, and I'm hoping someone might help me solve. Currently, I have something like this
somedata=
{test1: {good: 3, bad: 2, redo: 2}}
{test2: {good: 4, bad: 3}}
{test3: {good: 3, redo: 4}}
into something like
series:
[{name: "good", data: [3,4,3]},
{name: "bad", data: [2,3,0]},
{name: "redo", data: [2,0,4]}]
I can grab the categories by using Object.keys(somedata) easy enough i.e. ['test1', 'test2', 'test3'] but having problem formatting the rest of the data. I tried something like
let combine = {};
Object.values(somedata).map((row) => {
for (const [key, value] of Object.entries(row)) {
combine.hasOwnProperty(key)
? combine[key].push(value)
: (combine[key] = [value]);
}
console.log("combined", combine);
});
but quickly realized that it won't add 0 when key doesn't exist, which is required for the chart to compare between the different series, such as bar charts. So, any help is appreciated.
You can first collect all unique values and then using array#reduce and other array methods generate all the values corresponding to each key in an object accumaltor.
const somedata = [{test1: {good: 3, bad: 2, redo: 2}}, {test2: {good: 4, bad: 3}}, {test3: {good: 3, redo: 4}}],
uniqueValues = [...new Set(
somedata.reduce((r,o) => {
Object.values(o).forEach(ob => {
r.push(...Object.keys(ob));
});
return r;
}, [])
)];
result = Object.values(somedata.reduce((r, o) => {
Object.values(o).forEach(ob => {
uniqueValues.forEach(k => {
r[k] = r[k] || { name: k, data: []};
ob[k] ? r[k].data.push(ob[k]): r[k].data.push(0);
});
});
return r;
},{}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
something like this: for each test, group categories (can optionally restrict to a subset) - assume Zero for missing category
const someData = {test1: {good: 3, bad: 2, redo: 2}, test2: {good: 4, bad: 3}, test3: {good: 3, redo: 4}};
function prepMyGraphData(data, fields) {
let out = {
}
for (const [k, el] of Object.entries(data)) {
const _fields = new Set((fields || Object.keys(el)).concat(Object.keys(out)));
for (const f of _fields) {
const v = el.hasOwnProperty(f) ? el[f] || 0 : 0 ; // own field or 0
if (out.hasOwnProperty(f)) {
out[f].data.push(v) // existing category
}else{
out[f] = {name: f, data: [v]} // new category entry
}
}
}
return Object.values(out)
}
let fields = ['good', 'bad', 'redo']; // OR, undefined, for ALL own properties
const data = prepMyGraphData(someData, fields);
Related
I have an array that looks like this,
['event_tag', 'workflow_tag', 'created_timestamp', 'success']
and an array of objects where the object looks like,
{
"created_timestamp": "2022-04-01T13:14:53.028002Z",
"workflow_tag": "dj807",
"event_tag": "refresh",
"success": true
}
What I am wanting to do is make the above object and any other objects in that array match the order of the values in the first array so the finished object should look like,
{
"event_tag": "refresh",
"workflow_tag": "dj807",
"created_timestamp": "2022-04-01T13:14:53.028002Z",
"success": true
}
I have tried the following so far,
const keys = ['event_tag', 'workflow_tag', 'created_timestamp', 'success'];
newRowData = parsedRows.reduce((obj, v) => {
obj[v] = keys[v];
return obj
}, {});
But this returns,
{[object Object]: undefined}
You could order the keys by constructing a new object inside of an Array#map:
const parsedRows = [ { a: 1, c: 3, d: 4, b: 2, }, { b: 6, a: 5, c: 7, d: 8, }, { d: 12, b: 10, a: 9, c: 11, }, ];
const order = ['a', 'b', 'c', 'd'];
let newData = parsedRows.map(row => {
let newRow = {};
for (let key of order) {
newRow[key] = row[key];
}
return newRow;
});
console.log(newData);
Instead of iterating over Rows, Iterate on keys either map/reduce.
const keys = ["event_tag", "workflow_tag", "created_timestamp", "success"];
const obj = {
created_timestamp: "2022-04-01T13:14:53.028002Z",
workflow_tag: "dj807",
event_tag: "refresh",
success: true,
};
const res = Object.assign({}, ...keys.map((key) => ({ [key]: obj[key] })));
console.log(res)
I have an array of objects like this:
const arrayOfObjects = [
{ A: 1, B: 2, C: 3 },
{ A: 3, B: 4, C: 1 }
]
And another array which is called "headers"
const headers = [
['A', 'B'],
['C']
]
I have to create an array similar to the first one but, with those objects splited by what headers have in it's arrays.
This should be the goal:
const result = [
[
{ A: 1, B: 2 },
{ C: 3 }
],
[
{ A: 3, B: 4 },
{ C: 1 }
]
]
I tried by doing a "base" array with:
const baseArray = []
headers.forEach((header) => {
const objFromHeader = {};
header.forEach((head) => {
objFromHeader[head] = 0;
});
baseArray.push(objFromHeader);
});
That will give me the result array but with 0 values for each key.
And then loop for the first array and put inside another array the base array with the correct values.
Then I wanted to fill each key according to the value that comes from arrayOfObjects but here is where I can't see how could I loop that array of objects and put the correct value. The only problem with that approach is that the result array will have some 0 values that come from the initiation array that I'm using, it would be better to me to only put the objects that actually have values and not 0 (I was thinking on another function to delete those keys with value = 0...)
How could I achieve it in a better way?
Fiddle:
https://jsfiddle.net/pmiranda/Lpscz6vt/
When iterating over an object, use findIndex on the headers to identify which index in the headers array the property being iterated over should go into. Create an object there if it doesn't exist yet, and set the property.
const arrayOfObjects = [
{ A: 1, B: 2, C:3 },
{ A: 3, B: 4, C:1 }
];
const headers = [
['A', 'B'],
['C']
];
const toResultItem = (object) => {
const resultItem = [];
for (const [key, value] of Object.entries(object)) {
const headersIndex = headers.findIndex(arr => arr.includes(key));
resultItem[headersIndex] ??= {};
resultItem[headersIndex][key] = value;
}
return resultItem;
};
console.log(arrayOfObjects.map(toResultItem));
const arrayOfObjects = [
{ A: 1, B: 2, C: 3 },
{ A: 3, B: 4, C: 1 },
];
const headers = [['A', 'B'], ['C', 'D']];
const result = arrayOfObjects.map((obj) =>
headers.map((header) =>
header.reduce((acc, key) => {
acc[key] = obj[key];
return Object.keys(acc).reduce((newAcc, key) => {
if (acc[key]) {
newAcc[key] = acc[key];
}
return newAcc;
}
, {});
}, {})
)
);
console.log(result);
Array.forEach implementation
Logic
Loop through arrayOfObjects array.
Inside that, loop through headers array.
Inside that, loop through each array in the headers array.
Create an empty object and assign the property from nodes in headers array with values from objects in arrayOfObjects array.
const arrayOfObjects = [
{ A: 1, B: 2, C: 3 },
{ A: 3, B: 4, C: 1 }
];
const headers = [
['A', 'B'],
['C']
];
const baseArray = []
arrayOfObjects.forEach((obj) => {
const childNode = [];
headers.forEach((head) => {
const node = {};
head.forEach((key) => node[key] = obj[key]);
childNode.push(node);
});
baseArray.push(childNode);
});
console.log(baseArray)
Array.map and Array.reduce implementation.
Using the same logic implementes in the above solution, we can rewrite this using Array.map and Array.reduce as below.
const arrayOfObjects = [
{ A: 1, B: 2, C: 3 },
{ A: 3, B: 4, C: 1 }
];
const headers = [
['A', 'B'],
['C']
];
const output = arrayOfObjects.map((obj) => {
return headers.map((header) => {
return header.reduce((acc, curr) => {
acc[curr] = obj[curr];
return acc;
}, {});
})
})
console.log(output);
I have a nested object look like this:
let obj = {
F:{
asian: {
"35-44": 1,
"55-": 1,
},
"asian/black": {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
M:{
asian: {
"35-44": 1,
"55-": 1,
},
white: {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
}
And I want to flatten the object to this:
res = {
F: 6,
M: 6,
asian: 4,
"asian/black": 4,
white: 4,
"0-24": 2,
"35-44": 4,
"45-54": 4,
"55-": 2,
}
That every value in res should be the sum of the deepest object values(F, M) and object values with the same key(0-24, 35-44...). I feel this can be done using recursion and just can't get it right. The code I write:
let returnVal = 0
const flatten = (obj, prefix = '', res = {}) => {
return Object.entries(obj).reduce((r, [key, val]) => {
if(typeof val === 'object'){
flatten(val, key, r)
} else {
res[key] = val
returnVal = val;
}
if (key in res) {
res[key] += returnVal
} else {
res[key] = 0
res[key] += returnVal
}
return r
}, res)
}
console.log(flatten(obj))
it will output:
result = {
"0-24": 2,
"35-44": 2,
"45-54": 4,
"55-": 2,
F: 2,
M: 2,
asian: 2,
"asian/black": 2,
white: 2,
}
F, M, and some other keys are not correct. Thanks!
Another, perhaps simpler, approach is as follows:
const consolidate = (obj, path = [], results = {}) =>
Object .entries (obj) .reduce ((results, [k, v]) =>
Object (v) === v
? consolidate (v, [...path, k], results)
: [...path, k] .reduce (
(results, n) => ({...results, [n] : (results[n] || 0) + v}),
results
),
results)
const data = {F: {asian: {"35-44": 1, "55-": 1}, "asian/black": {"0-24": 1, "35-44": 1, "45-54": 2}}, M: {asian: {"35-44": 1, "55-": 1}, white: {"0-24": 1, "35-44": 1, "45-54": 2}}}
console .log (consolidate (data))
.as-console-wrapper {min-height: 100% !important; top: 0}
We recursively track paths taken through the object, such as ['F', 'asian/black', '45-54'] or ['M', 'white'] or simply ['f'] as well as an object containing the final results. When we the value at the current node is an object, we recur, adding the current property name to the path. When it's not (for this data it must therefore hit a number), we hit a base case in which we take each node in the current path, and update the results object by adding that number to the value for the node in the results object, or setting it to the current value if that value doesn't exist.
There is a potential issue with the default parameters, as described in another Q & A. If someone tried to map the consolidate function directly over an array of input objects, it would fail. If this is a concern, it's easy enough to swap the default parameters for a wrapper function:
const _consolidate = (obj, path, results) =>
Object .entries (obj) .reduce ((results, [k, v]) =>
Object (v) === v
? _consolidate (v, [...path, k], results)
: [...path, k] .reduce (
(results, n) => ({...results, [n] : (results[n] || 0) + v}),
results
),
results)
const consolidate = (obj) =>
_consolidate (obj, [], {})
const data = {
F: {
asian: {
"35-44": 1,
"55-": 1,
},
"asian/black": {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
M: {
asian: {
"35-44": 1,
"55-": 1,
},
white: {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
};
const isObject = obj => Object.prototype.toString.call(obj) === "[object Object]";
function nestKeys(obj, parent = "") {
return Object.keys(obj).map(key => {
const k = parent.length ? [parent, key].join(".") : key;
if (!isObject(obj[key])) {
return k;
}
return nestKeys(obj[key], k);
}).flat();
}
function flatObj(obj) {
const map = {};
const keys = nestKeys(obj);
keys.forEach(nestedKey => {
const splited = nestedKey.split(".");
const val = splited.reduce((acc, cur) => acc[cur], obj);
splited.forEach(k => {
map[k] = (map[k] || 0) + val;
})
});
return map;
}
console.log(flatObj(data));
I have an array of array of objects similar to this:
arr = [{
val: 1,
ts: 123
}, {
val: 2,
ts: 125
}, {
val: 3,
ts: 120
}, {
val: 4,
ts: 113
}, {
val: 5,
ts: 117
}, {
val1: 6,
ts: 143
}, {
val1: 7,
ts: 193
}, {
val1: 8,
ts: 187
}, {
val1: 9,
ts: 115
}, {
val1: 10,
ts: 116
}]
The length of the array is always an even number. Now basically I'd like to split them in 2 halves
split1 = [{ val:1}, {val :2}, ......{val:5}]
split2 = [{val1:6},{val1:7},.......{val1:10}]
Now I have to map over these arrays and combine their fields(first item of array1 with first item of array2 and so on) into one single object and add an extra id to it such that result will look like
final = [{val:1, val1:6 , id:1} , {val:2, val1:7,id:3} , {val:3, val1:8,id:3},{val:4, val1:9,id:4},{val: 5, val1:10, id:5}]
This should hold for all arrays of even length and I want to make it a dynamic one. Keys will never be repeated inside source array
What I have tried is:
var res= a.splice(0, arr.length/2);
var c = a.map((val, ind) => { {val, res[ind]} })
Can someone guide here?
You can try this solution
const arr = [{ val: 1},{val: 2},{val: 3}, {val: 4} , {val:5},{ val1: 6},{val1: 7},{val1: 8}, {val1: 9} , {val1:10}]
const split = arr => [arr.slice(0, arr.length/2), arr.slice(arr.length/2, arr.length)]
const splitedArr = split(arr);
const merge = arr => {
const merged = []
for(let i = 0; i < arr[0].length; i++){
let newObj = {...arr[0][i], ...arr[1][i], id:(i+1)}
merged.push(newObj);
}
return merged;
}
const mergedArr = merge(splitedArr);
console.log(mergedArr);
You're quite close, some minor fixes
wrap map function implicit return with () instead of {}
for adding computed value you need to assign key name explicitly
need to destructure val or need to access val.val
const arr = [{ val: 1}, {val: 2}, {val: 3}, {val: 4}, {val: 5}, {val1: 6}, {val1: 7}, {val1: 8}, {val1: 9}, {val1: 10}];
const firstHalf = arr.slice(0, arr.length / 2);
const secondHalf = arr.slice(arr.length / 2);
const final = secondHalf.map((val, ind) => ({
...val,
...firstHalf[ind],
id: ind,
}))
console.log(final);
I have tried
var res= a.splice(0, arr.length/2);
var c = a.map((val, ind) => { {val, res[ind]} })
You're quite close. To make the map callback syntactically valid and create the desired object, it should be
var res = a.splice(0, arr.length/2);
var c = a.map((val, ind) => {
return {val: val.val, val1: res[ind].val1, id: ind+1};
})
or
var c = a.map((val, ind) => {
return Object.assign({id: ind+1}, val, res[ind]);
})
Is there a shorthand for accessing properties of an array of objects?
let o = [
{id: 1},
{id: 2},
{id: 3}
];
o.map(item => item.id); // [1, 2, 3]
Instead with some type of shorthand:
o[].id; // [1, 2, 3]
If not, is there a recommendation to add such a thing in the future?
This would pretty much accomplish what i want:
Object.defineProperty(Array, 'all', {
value: function(array) {
let allProperties = new Set();
let methods = {};
array.forEach(o => {
if(!(o instanceof Object)) return;
Object.keys(o).forEach(property => {
allProperties.add(property);
});
});
allProperties.forEach(property => {
methods[property] = array.map(o => {
if(!(o instanceof Object)) return o;
return o[property];
});
});
return methods;
}
});
So that:
let o = [
{id: 1},
{id: 2},
null,
{num: 3}
];
Array.all(o).id; // [1, 2, null, undefined]
It could also extend Array.prototype so that o.all.id would return the same thing.