I have a few empty objects in my JSON request:
FXP:
"createdBy": {},
I would like to before the request is sent to the server convert these empty objects into following structure:
"createdBy": null,
How can I do it recursively in whole object please?
Example:
{
"main": {
"id": null,
"archived": true,
"createdBy": {},
"creationTime": null,
"location": {
"id": 79,
"address": {
"id": 79,
"city": null,
"latitude": 50.072613888888895,
"longitude": 14.543111111111111,
"street": null,
"streetNumber": null,
"district": null
},
"bsc": "BSC123",
"code": null,
"indoorOutdoor": null,
"siteId": "A0RST",
"stationType": {
"id": 1,
"name": "Indoor solution"
},
"shared": false,
"sapSacIrnCode": "31049.0",
"abloyLocation": "NA",
"name": "A0RST"
},
"actionName": {},
"orderType": {},
"project": {
"id": 1,
"cards": [],
"color": null,
"managerCustomer": null,
"managerSuntel": null,
"heliosSync": false,
"name": "Vodafone Test",
"parentProject": null,
"team": null,
"facility": {
"id": 1,
"code": 110,
"name": "110_MANAGEMENT"
},
"workers": []
},
"note": "",
"orderNumber": "2626262"
},
"milestoneSequence": {},
"milestones": []
}
In JSON.parse resp. JSON.stringify you can pass a function as the 2nd argument.
This function gets name and value as arguments.
So you can adjust the values during parsing resp. stringifying.
Here is a recursive function that might help you:
function nullify (obj) {
for(key in obj) {
if(JSON.stringify(obj[key])=="{}") {
obj[key] = null;
} else if (typeof obj[key] == "object" && !Date.parse(obj[key])) {
obj[key] = nullify(obj[key]);
}
}
return obj;
}
for this example :
var obj = {
"b": 1,
"c": {},
"d": {
"a": 1,
"b": {},
"c": {
"x": 1,
"y": {}
}
}
}
the result of nullify(obj); is
{
"b": 1,
"c": null,
"d": {
"a": 1,
"b": null,
"c": {
"x": 1,
"y": null
}
}
}
If you don't like using strings too much:
function emptyObjToNull(object){
var isObject, hasKeys, isArray, current;
for(var k in object){
if(!object.hasOwnProperty(k))
return;
current = object[k];
isObject = typeof current == 'object';
hasKeys = isObject && Object.keys(current).length !== 0;
isArray = isObject && Object.prototype.toString.call(current) === "[object Array]";
if(hasKeys){
emptyObjToNull(current);
}else if(isArray){
for(var i = current.length; i--;){
emptyObjToNull(current);
}
}else if(isObject && !hasKeys){
object[k] = null; // Set the key directly, not the reference
}
}
}
Fiddle: http://jsfiddle.net/cfvm3r63/3/
Here is a solution using object-scan. Depending on your scenario using a dependency might make sense
// const objectScan = require('object-scan');
const data = {"main":{"id":null,"archived":true,"createdBy":{},"creationTime":null,"location":{"id":79,"address":{"id":79,"city":null,"latitude":50.072613888888895,"longitude":14.543111111111111,"street":null,"streetNumber":null,"district":null},"bsc":"BSC123","code":null,"indoorOutdoor":null,"siteId":"A0RST","stationType":{"id":1,"name":"Indoor solution"},"shared":false,"sapSacIrnCode":"31049.0","abloyLocation":"NA","name":"A0RST"},"actionName":{},"orderType":{},"project":{"id":1,"cards":[],"color":null,"managerCustomer":null,"managerSuntel":null,"heliosSync":false,"name":"Vodafone Test","parentProject":null,"team":null,"facility":{"id":1,"code":110,"name":"110_MANAGEMENT"},"workers":[]},"note":"","orderNumber":"2626262"},"milestoneSequence":{},"milestones":[]};
const nullify = (input) => objectScan(['**'], {
rtn: 'count',
filterFn: ({ value, parent, property }) => {
if (
value instanceof Object
&& !Array.isArray(value)
&& Object.keys(value).length === 0
) {
parent[property] = null;
return true;
}
return false;
}
})(input);
console.log(nullify(data)); // returns number of changes
// => 4
console.log(data);
// => { main: { id: null, archived: true, createdBy: null, creationTime: null, location: { id: 79, address: { id: 79, city: null, latitude: 50.072613888888895, longitude: 14.543111111111111, street: null, streetNumber: null, district: null }, bsc: 'BSC123', code: null, indoorOutdoor: null, siteId: 'A0RST', stationType: { id: 1, name: 'Indoor solution' }, shared: false, sapSacIrnCode: '31049.0', abloyLocation: 'NA', name: 'A0RST' }, actionName: null, orderType: null, project: { id: 1, cards: [], color: null, managerCustomer: null, managerSuntel: null, heliosSync: false, name: 'Vodafone Test', parentProject: null, team: null, facility: { id: 1, code: 110, name: '110_MANAGEMENT' }, workers: [] }, note: '', orderNumber: '2626262' }, milestoneSequence: null, milestones: [] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan
Related
I need to parse some data got from BE from one format to another to can inject it into a table component. The format received is:
{
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123,
"children": []
}
]
}
]
}
and I need the following format:
{
"key": "Income",
"data": {
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null
},
"children": [
{
"key": "4000 Revenue",
"data": {
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null
},
"children": [
{
"key": "4100 Product 1 Revenue",
"data": {
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123
},
"children": []
}
]
}
]
}
Each parent can have more children or no children.
I tried to do something with reduce, but no result. This is what I've tried:
const prepareTableValue = (data: any): any => {
const res = data.reduce((result: any, node) => {
if (node.children) {
result.push({
key: node.displayName,
data: {
displayName: node.displayName,
baseBersionSum: node.baseVersionSum,
comparisonVersionSum: node.comparisonVersionSum,
variance: node.variance,
variancePercent: node.variancePercent,
},
children: node.children,
});
prepareTableValue(node.children);
}
return result;
}, []);
return res;
};
Thanks in advance!
Nice challenge ! Here is a solution with a recursive function that creates a new object and adds to it recursively by going through each child of the initial object and calling itself for that child and the child in that position in the new object:
const objToFormat = {
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123,
"children": []
}
]
}
]
};
const formatData = (objToFormat, formattedObj = {}) => {
const { displayName, children, ...data } = objToFormat;
formattedObj.key = displayName;
formattedObj.data = { displayName, ...data };
formattedObj.children = [];
children.forEach((child, i) => {
formattedObj.children[i] = {};
formatData(child, formattedObj.children[i]);
})
return formattedObj;
}
console.log(formatData(objToFormat))
A recursive parse should work.
function parseData(items: any[]) {
const parsed = items.map((item) => {
const clone = Object.create(item);
clone.key = clone.displayName;
clone.data = {
displayName: clone.displayName,
baseBersionSum: clone.baseVersionSum,
comparisonVersionSum: clone.comparisonVersionSum,
variance: clone.variance,
variancePercent: clone.variancePercent,
};
clone.children = parseData(clone.children);
return clone;
});
return parsed;
}
I am trying to return an array of objects where, for a particular property on each object, the value is not null and is not an empty string. Actually trimming the string in cases where it contains multiple white spaces is tricky. I've got it mostly going, but the only problem is that now my "good" string value is having it's whitespace removed as well, so two words get mushed into one.
In my use case I only want to remove the white space if there are no other characters in the string. This is what I have:
const goalNotes = [
{
"goal": {
"lastUpdate": 1,
"value": " ",
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
},
{
"goal": {
"lastUpdate": 1,
"value": null,
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
},
{
"goal": {
"lastUpdate": 1,
"value": "Something here!",
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
}
];
let goalValues = goalNotes
.filter(gn => gn.goal.value !== null)
.filter(gn => gn.goal.value = gn.goal.value.replace(/\s+/g, ''))
.filter(gn => gn.goal.value !== '');
What I get in the end (this is the correct object, but the value, which contained two words, has been mushed into one):
[{
goal: {
lastUpdate: 1,
value: "Somethinghere!" // two words mushed together
},
guid: "4a0c6410-6668-47e0-bbf7-0d27defc7a05"
}]
You can use array#filter and string#trim to remove the empty and null string. If optional chaining is supported then we can use below:
goalNotes.filter(({goal: {value}}) => value?.trim())
const goalNotes = [{ "goal": { "lastUpdate": 1, "value": " ", }, "guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05", }, { "goal": { "lastUpdate": 1, "value": null, }, "guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05", }, { "goal": { "lastUpdate": 1, "value": "Something here!", }, "guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05", } ],
result = goalNotes.filter(({goal: {value}}) => value && value.trim());
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can also use /\B\s+|\s+\B/g to remove space only at the beginning and end of the string.
const goalNotes = [
{
"goal": {
"lastUpdate": 1,
"value": " ",
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
},
{
"goal": {
"lastUpdate": 1,
"value": null,
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
},
{
"goal": {
"lastUpdate": 1,
"value": "Something here!",
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
}
];
let goalValues = goalNotes
.filter(gn => gn.goal.value !== null)
.filter(gn => gn.goal.value = gn.goal.value.replace(/\B\s+|\s+\B/g, ''))
.filter(gn => gn.goal.value !== '');
console.log(goalValues);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do all the checks in "one" .filter() call
const goalNotes = [
{
"goal": {
"lastUpdate": 1,
"value": " ",
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
},
{
"goal": {
"lastUpdate": 1,
"value": null,
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
},
{
"goal": {
"lastUpdate": 1,
"value": "Something here!",
},
"guid": "4a0c6410-6668-47e0-bbf7-0d27defc7a05",
}
];
const result = goalNotes.filter( item => {
if (
item.goal.value // check if not null or undefined
&& ( // and if it is not null or undefind..
'string' === typeof(item.goal.value) // check if it is a string
&& 0 !== item.goal.value.trim().length // if it is a string check trim length is not 0
)
) { return item }
});
console.log(result)
How to make nested object null
if object attributes has a null values. please check the JSON below
I have JSON data as following
[{
"student": {
"id": null,
"name": null
},
"children": [{
"student": null,
"children": [{
"student": {
"id": 1,
"name": "A"
}
},
{
"student": {
"id": null,
"name": null
}
}
]
}]
}]
I want to convert it to following output
Expected
[{
"student": null,
"children": [{
"student": null,
"children": [{
"student": {
"id": 1,
"name": "A"
}
},
{
"student": null
}
]
}]
}]
You could "nullify" values if their values are all null using the following conditional.
Object.values(obj).every(value => value == null)
I created a basic recursive function to below that traverses the object and checks to see if it needs to nullify an object. This is all done in-place, and it will modify the original object.
const obj = [{
"student": { "id": null, "name": null },
"children": [{
"student": null,
"children": [
{ "student": { "id": 1, "name": "A" } },
{ "student": { "id": null, "name": null } }
]
}]
}];
const nullify = (obj, key = null, parent = null) => {
if (obj != null) {
if (Array.isArray(obj)) {
obj.forEach((item, index) => nullify(item, index, obj));
} else if (typeof obj === 'object') {
if (Object.values(obj).every(value => value == null)) {
parent[key] = null;
} else {
Object.entries(obj).forEach(([key, value]) => nullify(value, key, obj));
}
}
}
};
nullify(obj);
console.log(obj);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Here is an iterative solution using object-scan
// const objectScan = require('object-scan');
const data = [{ student: { id: null, name: null }, children: [{ student: null, children: [{ student: { id: 1, name: 'A' } }, { student: { id: null, name: null } }] }] }];
const nullify = objectScan(['**(^children$).student'], {
useArraySelector: false,
rtn: 'count',
filterFn: ({ parent, property, value }) => {
if (
value instanceof Object
&& !Array.isArray(value)
&& Object.values(value).every((e) => e === null)
) {
parent[property] = null;
return true;
}
return false;
}
});
console.log(nullify(data));
// => 2
console.log(data);
// => [ { student: null, children: [ { student: null, children: [ { student: { id: 1, name: 'A' } }, { student: null } ] } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.3.1"></script>
Disclaimer: I'm the author of object-scan
i am having JSON Object in the form of
{
"detailObject": {
"user": {
"userProperty": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "4 hrs"
}
},
"userRegion": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "5 hrs"
}
}
},
"OtherInfo": [
{
"year": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
},
"volume": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
}
}
]
}
}
Now i want to map it in a single object like {"userProperty":"4 hrs","userRegion":"5 hrs","year":"","volume":""} i.e parent key and duration
or [{"userProperty":"4 hrs"},{"userRegion":"5 hrs"},{"year":""},{"volume":""}]
You could do the exhausive traverse through the data object:
the base condition is to stop when a checked value is not an array and object
if the value to check is an array, continue to traverse through each element
if the value is an object, check if it contains the non-undefined path of active.duration, if the that condition is met, store the key and the value achieved from that path
const res = []
const exhausiveTraverse = (data) => {
if (isArray(data)) {
data.map((el) => exhausiveTraverse(el))
} else if (isObject(data)) {
Object.entries(data).map(([key, value]) => {
if (getByPath(value, ["active", "duration"]) !== undefined) {
res.push({ [key]: getByPath(value, ["active", "duration"]) })
} else {
exhausiveTraverse(value)
}
})
} else {
return undefined
}
}
Full code
const data = {
detailObject: {
user: {
userProperty: {
active: {
id: "3be0d467",
value: null,
duration: "4 hrs",
},
},
userRegion: {
active: {
id: "3be0d467",
value: null,
duration: "5 hrs",
},
},
},
OtherInfo: [
{
year: {
active: {
id: "3be0d467",
value: null,
duration: "",
},
},
volume: {
active: {
id: "3be0d467",
value: null,
duration: "",
},
},
},
],
},
}
const isArray = (arr) => Array.isArray(arr)
const isObject = (obj) =>
typeof obj === "object" && obj !== null && !Array.isArray(obj)
const getByPath = (obj, path) => {
try {
return path.reduce((acc, p) => acc[p], obj)
} catch (err) {
return undefined
}
}
const res = []
const exhausiveTraverse = (data) => {
if (isArray(data)) {
data.map((el) => exhausiveTraverse(el))
} else if (isObject(data)) {
Object.entries(data).map(([key, value]) => {
if (getByPath(value, ["active", "duration"]) !== undefined) {
res.push({ [key]: getByPath(value, ["active", "duration"]) })
} else {
exhausiveTraverse(value)
}
})
} else {
return undefined
}
}
exhausiveTraverse(data)
console.log(res)
You can do this by looping through the object's properties.
Note: This assumes that your object will always look the way you described it above, where:
detailObject.user is an object of sub-objects, where each sub-object has subObject.active.duration
detailObject.OtherInfo is an array of one object, where the object has object.active.duration
In this example, I use Object.entries().
const myObject = {
"detailObject": {
"user": {
"userProperty": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "4 hrs"
}
},
"userRegion": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "5 hrs"
}
}
},
"OtherInfo": [
{
"year": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
},
"volume": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
}
}
]
}
};
const results = {};
for (const [userDataName, userData] of Object.entries(myObject.detailObject.user)) {
results[userDataName] = userData.active.duration;
}
for (const [userDataName, userData] of Object.entries(myObject.detailObject.OtherInfo[0])) {
results[userDataName] = userData.active.duration;
}
console.log(JSON.stringify(results, null, '\t'));
Since the object has different types of data, they must be converted to the same type. I use flat to move the array at OtherInfo to a higher level. Then collect a new object using reduce.
const myObject = {
"detailObject": {
"user": {
"userProperty": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "4 hrs"
}
},
"userRegion": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "5 hrs"
}
}
},
"OtherInfo": [{
"year": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
},
"volume": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
}
}]
}
};
const result = Object.values(myObject.detailObject)
.flat(Infinity)
.reduce((obj, value) => (Object.entries(value).forEach(item => obj[item[0]] = item[1].active.duration), obj), {});
console.log(result);
Recursive approach will be helpful here. Use Object.entries and recursively check for "active" and "duration" keys.
const recuriveAdd = (obj, res) => {
if (Array.isArray(obj)) {
obj.forEach((item) => recuriveAdd(item, res));
} else {
Object.entries(obj).forEach(([key, value]) => {
if ("active" in value) {
res.push({ [key]: value.active.duration });
} else {
Object.values(value).forEach((item) => recuriveAdd(item, res));
}
});
}
};
obj = {
detailObject: {
user: {
userProperty: {
active: {
id: "3be0d467",
value: null,
duration: "4 hrs",
},
},
userRegion: {
active: {
id: "3be0d467",
value: null,
duration: "5 hrs",
},
},
},
OtherInfo: [
{
year: {
active: {
id: "3be0d467",
value: null,
duration: "",
},
},
volume: {
active: {
id: "3be0d467",
value: null,
duration: "",
},
},
},
],
},
};
const res = [];
recuriveAdd(obj, res);
console.log(res);
Try this out.
const jsonObj = {
"detailObject": {
"user": {
"userProperty": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "4 hrs"
}
},
"userRegion": {
"active": {
"id": "3be0d467",
"value": null,
"duration": "5 hrs"
}
}
},
"OtherInfo": [{
"year": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
},
"volume": {
"active": {
"id": "3be0d467",
"value": null,
"duration": ""
}
}
}]
}
};
const {detailObject: {user}} = jsonObj;
const {detailObject: {OtherInfo: [other]}} = jsonObj;
const customObj = {...user, ...other};
const myObj = (
({
userProperty: {active: {duration: propDur}},
userRegion: {active: {duration: regDur}},
year: {active: {duration: yearDur}},
volume: {active: {duration: volDur}}
}) => ({
userProperty: propDur,
userRegion: regDur,
year: yearDur,
volume: volDur
})
)(customObj);
console.log(myObj);
I think the best solution should be using destructuring of objects. I created myObj, the one that you need, using IIFE.
Using my approach you can also declare a default value for a key, if not found in the jsonObj.
i have a big problem to manipulate a js object. I have this object :
"daily_operator_trend": {
"2018-08-01": {},
"2018-08-02": {},
"2018-07-16": {
"1": 1,
"2": 4,
"3": 3
},
"2018-07-18": {
"1": 1,
"3": 7
}
},
"operatorStats": [
{
"min_response_time": 5,
"max_deepness": 3,
"max_response_time": 5,
"min_deepness": 3,
"details": {
"phoneNumber": "001122333",
"allBots": true,
"surname": "Sky",
"nickname": "jesky",
"name": "Je",
"type": "owner",
"operatorId": 1,
"userId": "834f6de213c7d79bd64031371773b154",
"email": "jesky#hotmail.it",
"maxConversation": -1,
"botIdList": [
"1ec0e59069561da21727e3a56d05ef2d",
"0ddfc38f54f51f7b40e1057436b34a6f",
"37c43963d3e716bc4e41e1e6a32ed7f1"
]
},
"avg_deepness": 3,
"avg_response_time": 5
}]
Where in daily_operator_trend we have a key like a datae and a value is an object, in this object the key is the operator id and value is the num of conversation. I need to manipulate and transform it in a new array of object like this :
series: [ {name:'jesky', data:[0,0,1,1]}]
I'm trying with this code:
let columnDataConv = data.operatorStats.reduce(function(map, obj){
let newObj = [];
let cData = Object.keys(data.daily_operator_trend).reduce(function(m, o){
m['name'] = '';
m['data'] = [];
for (let [key, value] of Object.entries(data.daily_operator_trend[o])){
if (key == obj.details.operatorId){
if ( obj.details.nickname in m){
m['data'].push(value);
}else {
m['name']= obj.details.nickname;
m['data'].push(value);
}
}else {
m['data'].push(0);
}
newObj.push(m);
}
return newObj;
}, {})
map={...cData};
return map;
}, {});
Can you help me ?
const data = {
"daily_operator_trend": {
"2018-08-01": {
"1": 1,
"2": 4,
"3": 3
},
"2018-08-02": {
"1": 10,
"2":15,
"3":25
},
"2018-07-16": {
},
},
"operatorStats": [
{
"min_response_time": 5,
"max_deepness": 3,
"max_response_time": 5,
"min_deepness": 3,
"details": {
"phoneNumber": "001122333",
"allBots": true,
"surname": "Sky",
"nickname": "jesky",
"name": "Je",
"type": "owner",
"operatorId": 1,
"userId": "834f6de213c7d79bd64031371773b154",
"email": "jesky#hotmail.it",
"maxConversation": -1,
"botIdList": [
"1ec0e59069561da21727e3a56d05ef2d",
"0ddfc38f54f51f7b40e1057436b34a6f",
"37c43963d3e716bc4e41e1e6a32ed7f1"
]
},
"avg_deepness": 3,
"avg_response_time": 5
},
{
"min_response_time": 4,
"max_deepness": 2,
"max_response_time": 1,
"min_deepness": 2,
"details": {
"phoneNumber": "001122333",
"allBots": true,
"surname": "SkyWine",
"nickname": "john",
"name": "Jeremy",
"type": "owner",
"operatorId": 2,
"userId": "834f6de213c7d79bd64031371773b155",
"email": "john#hotmail.it",
"maxConversation": -1,
"botIdList": [
"1ec0e59069561da21727e3a56d05ef2d",
"0ddfc38f54f51f7b40e1057436b34a6g",
"37c43963d3e716bc4e41e1e6a32ed7f1"
]
},
"avg_deepness": 3,
"avg_response_time": 5
},
{
"min_response_time": 4,
"max_deepness": 2,
"max_response_time": 1,
"min_deepness": 5,
"details": {
"phoneNumber": "001122333",
"allBots": true,
"surname": "SkyWine",
"nickname": "Frank",
"name": "Jeremy",
"type": "owner",
"operatorId": 3,
"userId": "834f6de213c7d79bd64031371773b156",
"email": "frank#hotmail.it",
"maxConversation": -1,
"botIdList": [
"1ec0e59069561da21727e3a56d05ef2d",
"0ddfc38f54f51f7b40e1057436b34a6f",
"37c43963d3e716bc4e41e1e6a32ed7f2"
]
},
"avg_deepness": 3,
"avg_esponse_time": 5
}
]
};
function mergeNames (arr) {
return _.chain(arr).groupBy('name').mapValues(function (v) {
return _.chain(v).pluck('value').flattenDeep();
}).value();
}
let newObj = [];
let columnDataConv = data.operatorStats.reduce(function(map, obj){
for (let [k,v] of Object.entries(data.daily_operator_trend)){
for (let [key, value] of Object.entries(v)){
let m = {};
let dati = [];
if (key == obj.details.operatorId){
if(newObj.length > 0){
for(let i = 0;i< newObj.length; ++i){
if(newObj[i].name === obj.details.nickname){
dati=[];
dati.push(value);
newObj[i].data.push(...dati);
break;
}else{
dati=[];
m = {};
m['name']= obj.details.nickname;
dati.push(value);
m['data']=dati;
newObj.push(m);
break;
}
};
}else{
dati=[];
m = {};
m['name']= obj.details.nickname;
dati.push(value);
m['data']=dati;
newObj.push(m);
break;
}
}
}
}
map={...newObj};
return map;
}, []);
console.log(columnDataConv);
Now i have the array of objects but only the first entry of my array is correct. Why the other element aren't merged?