I want to summarize an array of objects and return the number of object occurrences in another array of objects. What is the best way to do this?
From this
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
To this
var newArrayOfSongs = [
{"title": "Blue", "playCount": 3 },
{"title": "Green", "playCount": 1}
]
I have tried
arrayOfSongs.reduce(function(acc, cv) {
acc[cv.title] = (acc[cv.title] || 0) + 1;
return acc;
}, {});
}
But it returns an object:
{ "Blue": 3, "Green": 1};
You should pass the initial argument to the reduce function as an array instead of object and filter array for the existing value as below,
Working snippet:
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
var newArrayOfSongs = arrayOfSongs.reduce(function(acc, cv) {
var arr = acc.filter(function(obj) {
return obj.title === cv.title;
});
if(arr.length === 0) {
acc.push({title: cv.title, playCount: 1});
} else {
arr[0].playCount += 1;
}
return acc;
}, []);
console.log(newArrayOfSongs);
To build on what you already have done, the next step is to "convert" the object to an array
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
var obj = arrayOfSongs.reduce(function(acc, cv) {
acc[cv.title] = (acc[cv.title] || 0) + 1;
return acc;
}, {});
// *** added code starts here ***
var newArrayOfSongs = Object.keys(obj).map(function(title) {
return {
title: title,
playCount:obj[title]
};
});
console.log(newArrayOfSongs);
I recommend doing this in two stages. First, chunk the array by title, then map the chunks into the output you want. This will really help you in future changes. Doing this all in one pass is highly complex and will increase the chance of messing up in the future.
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
function chunkByAttribute(arr, attr) {
return arr.reduce(function(acc, e) {
acc[e[attr]] = acc[e[attr]] || [];
acc[e[attr]].push(e);
return acc;
}, {});
}
var songsByTitle = chunkByAttribute(arrayOfSongs, 'title');
var formattedOutput = Object.keys(songsByTitle).map(function (title) {
return {
title: title,
playCount: songsByTitle[title].length
};
});
There, now everything is named according to what it does, everything does just one thing, and is a bit easier to follow.
https://jsfiddle.net/93e35wcq/
I used a set object to get the unique track titles, then used Array.map to splice those and return a song object that contains play count inside the track title.
The Data:
var arrayOfSongs = [{
"title": "Blue",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}, {
"title": "Blue",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}, {
"title": "Blue",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}, {
"title": "Green",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}];
The Function:
function getPlayCount(arrayOfSongs) {
let songObj = {};
let SongSet = new Set();
arrayOfSongs.map(obj => (SongSet.has(obj.title)) ? true : SongSet.add(obj.title));
for (let songTitle of SongSet.values()) {
songObj[songTitle] = {
playCount: 0
};
arrayOfSongs.map(obj => (obj.title === songTitle) ? songObj[songTitle].playCount++ : false)
}
return songObj;
}
console.log(getPlayCount(arrayOfSongs));
Which isn't exactly what you wanted formatting wise, but if you're married to it, this will do the trick:
function getPlayCount(arrayOfSongs) {
let songObj = {};
let SongSet = new Set();
arrayOfSongs.map(obj => (SongSet.has(obj.title)) ? true : SongSet.add(obj.title));
for (let songTitle of SongSet.values()) {
songObj[songTitle] = 0;
arrayOfSongs.map(obj => (obj.title === songTitle) ? songObj[songTitle]++ : false)
}
return songObj;
}
console.log(getPlayCount(arrayOfSongs));
https://jsfiddle.net/93e35wcq/1/
Related
I have this simplified array of objects
var items = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"}, {"function":"function_2","process":"process_3"}, {"function":"function_2","process":"process_4"}]
that I want to map in JS according to the keys into the following array:
result = [
{
"function":"function_1",
"process": [
"process_1",
"process_2"
]
},
{
"function":"function_2",
"process": [
"process_3",
"process_4"
]
}
]
Dedicated to you my friend
var items = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"}, {"function":"function_2","process":"process_3"}, {"function":"function_2","process":"process_4"}]
var arr2 = items.reduce( (a,b) => {
var i = a.findIndex( x => x.function === b.function);
return i === -1 ? a.push({ function : b.function, process : [b.process] }) : a[i].process.push(b.process), a;
}, []);
console.log(arr2)
var items = [{
"function": "function_1",
"process": "process_1"
}, {
"function": "function_1",
"process": "process_2"
}, {
"function": "function_1",
"process": "process_3"
}, {
"function": "function_2",
"process": "process_3"
}, {
"function": "function_2",
"process": "process_4"
}]
var uniqueFunctionList = [] // to keep track of unique function names
var resultArr = []
items.forEach(item => {
if (!uniqueFunctionList.includes(item.function)) { // item object doesnt exist
uniqueFunctionList.push(item.function) // add unique function name
let tmp_obj = {}
tmp_obj['function'] = item.function // item is unique just push it
tmp_obj['process'] = [item.process] // make process array via []
resultArr.push(tmp_obj)
} else { // function name is not unique
resultArr.forEach(result => { // it is available in resultArr
if (result.function == item.function) { // find the function
result.process.push(item.process) // push to process array
}
})
}
})
console.log(resultArr)
I have a nested array and what I was trying to do was get all the values of the object embedded inside the array. I am currently getting each embedded object and calling Object.values to get the values but this method isn't efficient when the array size is big. Is there a way to loop through the array and return the values of each object? Any help is appreciated. Thanks in advance.
const data = [{"path":"uploads\\20211115000755-package.json"},{"path":"uploads\\20211115012255-index.html"},{"path":"uploads\\20211115014342-dataServerMid.js"},{"path":"uploads\\20211115031212-index.js"},{"path":"uploads\\20211115031218-uploadDataServer.js"},{"path":"uploads\\20211115031232-index.js"},{"path":"uploads\\20211115031244-dataServerMid.js"},{"path":"uploads\\20211115031250-uploadData.css"},{"path":"uploads\\20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115031318-20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115050204-exportsCapture.JPG"},{"path":"uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"},{"path":"uploads\\20211115200304-Readme.docx"},{"path":"uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"},{"path":"uploads\\20211115203354-ln command examples.docx"},{"path":"uploads\\20211115210027-Q2.docx"},{"path":"uploads\\20211116011817-Fall 2019 ABCD Plattsburgh Syllabi Course Description.docx"}]
//change this to loop and return all the values instead of having to call by index
const dataValues = [Object.values(data[0]).toString(), Object.values(data[1]).toString(), Object.values(data[2]).toString()]
console.log(dataValues)
UPDATE: I tried #yousaf's method. It worked for my 3 item array but not for this:
const data = [{
"path": "uploads\\20211115000755-package.json"
}, {
"path": "uploads\\20211115012255-index.html"
}, {
"path": "uploads\\20211115014342-dataServerMid.js"
}, {
"path": "uploads\\20211115031212-index.js"
}, {
"path": "uploads\\20211115031218-uploadDataServer.js"
}, {
"path": "uploads\\20211115031232-index.js"
}, {
"path": "uploads\\20211115031244-dataServerMid.js"
}, {
"path": "uploads\\20211115031250-uploadData.css"
}, {
"path": "uploads\\20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115031318-20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115050204-exportsCapture.JPG"
}, {
"path": "uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"
}, {
"path": "uploads\\20211115200304-Readme.docx"
}, {
"path": "uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"
}, {
"path": "uploads\\20211115203354-ln command examples.docx"
}, {
"path": "uploads\\20211115210027-Q2.docx"
}, {
"path": "uploads\\20211116011817-Fall 2019.docx"
}]
//change this to loop and return all the values instead of having to call by index
const dataValues = data.map((obj, idx) => obj["path" + (idx + 1)])
console.log(dataValues)
Use a for...of to iterate over the array, and then push the value to a new array.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = [];
for (const obj of data) {
const [value] = Object.values(obj);
arr.push(value);
}
console.log(arr);
Or you can use map.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = data.map(obj => {
const [value] = Object.values(obj);
return value;
});
console.log(arr);
Use for loop for iterate data
const data = [{
"path1": "uploads\\20211115000755-package.json"
}, {
"path2": "uploads\\20211115012255-index.html"
}, {
"path3": "uploads\\20211115014342-dataServerMid.js"
}]
const dataValues = [];
for(var i = 0; i < data.length; i++)
{
dataValues.push(Object.values(data[i]).toString())
}
console.log(dataValues)
This may help You. Try it out..
function nestedLoop(obj) {
const res = {};
function recurse(obj, current) {
for (const key in obj) {
let value = obj[key];
if(value != undefined) {
if (value && typeof value === 'object') {
recurse(value, key);
} else {
// Do your stuff here to var value
res[key] = value;
}
}
}
}
recurse(obj);
return res;
}
I am stuck to solve this problem.
Convert an array below
var input = [
'animal/mammal/dog',
'animal/mammal/cat/tiger',
'animal/mammal/cat/lion',
'animal/mammal/elephant',
'animal/reptile',
'plant/sunflower'
]
to json Object
var expectedResult = {
"animal": {
"mammal": {
"dog": true,
"cat": {
"tiger": true,
"lion": true
},
"elephant": true
},
"reptile": true
},
"plant": {
"sunflower": true
}
}
Which data structure and algorithm can I apply for it?
Thanks
You need to first split each element to convert to array
using reverse reduce method you can convert them to object.
And your last step is merge this objects.
Lodash.js merge method is an one way to merge them.
var input = ['animal/mammal/dog','animal/mammal/cat/tiger','animal/mammal/cat/lion', 'animal/mammal/elephant','animal/reptile', 'plant/sunflower']
var finalbyLodash={}
input.forEach(x=>{
const keys = x.split("/");
const result = keys.reverse().reduce((res, key) => ({[key]: res}), true);
finalbyLodash = _.merge({}, finalbyLodash, result);
});
console.log(finalbyLodash);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
To make the process more understandable, break the problem down into pieces.
The first step is convert each string into something we can use, converting this:
"animal/mammal/dog"
into this:
[ "animal", "mammal", "dog" ]
That's an array of property names needed to build the final object.
Two functions will accomplish this for you, String.prototype.split() to split the string into an array, and Array.prototype.map() to transform each of the array elements:
let splitIntoNames = input.map(str => str.split('/'));
The intermediate result is this:
[
[ "animal", "mammal", "dog" ],
[ "animal", "mammal", "cat", "tiger" ],
[ "animal", "mammal", "cat", "lion" ],
[ "animal", "mammal", "elephant" ],
[ "animal", "reptile" ],
[ "plant", "sunflower" ]
]
Next step is to iterate over each array, using Array.prototype.forEach() to add properties to the object. You could add properties to the object with a for loop, but let's do that with a recursive function addName():
function addName(element, list, index) {
if (index >= list.length) {
return;
}
let name = list[index];
let isEndOfList = index === list.length - 1;
element[name] = element[name] || (isEndOfList ? true : {});
addName(element[name], list, index + 1);
}
let result = {};
splitIntoNames.forEach((list) => {
addName(result, list, 0);
});
The result:
result: {
"animal": {
"mammal": {
"dog": true,
"cat": {
"tiger": true,
"lion": true
},
"elephant": true
},
"reptile": true
},
"plant": {
"sunflower": true
}
}
const input = [
"animal/mammal/dog",
"animal/mammal/cat/tiger",
"animal/mammal/cat/lion",
"animal/mammal/elephant",
"animal/reptile",
"plant/sunflower",
];
let splitIntoNames = input.map((str) => str.split("/"));
console.log("splitIntoNames:", JSON.stringify(splitIntoNames, null, 2));
function addName(element, list, index) {
if (index >= list.length) {
return;
}
let name = list[index];
let isEndOfList = index === list.length - 1;
element[name] = element[name] || (isEndOfList ? true : {});
addName(element[name], list, index + 1);
}
let result = {};
splitIntoNames.forEach((list) => {
addName(result, list, 0);
});
console.log("result:", JSON.stringify(result, null, 2));
You can create a function that will slice every element from the array by "/" than you put the results into a variable and than just mount the Json. I mean something like that below:
window.onload = function() {
var expectedResult;
var input = [
'animal/mammal/dog',
'animal/mammal/cat/tiger',
'animal/mammal/cat/lion',
'animal/mammal/elephant',
'animal/reptile',
'plant/sunflower'
]
input.forEach(element => {
var data = element.split('/');
var dog = data[2] === 'dog' ? true : false
var tiger = data[2] === 'cat' && data[3] === 'tiger' ? true : false
var lion = data[2] === 'cat' && data[3] === 'lion' ? true : false
expectedResult = {
data[0]: {
data[1]: {
"dog": dog,
"cat": {
"tiger": tiger,
"lion": lion
}
}
}
}
})
}
Late to the party, here is my try. I'm implmenting recursive approach:
var input = ['animal/mammal/dog', 'animal/mammal/cat/tiger', 'animal/mammal/cat/lion', 'animal/mammal/elephant', 'animal/reptile', 'plant/sunflower'];
result = (buildObj = (array, Obj = {}) => {
array.forEach((val) => {
keys = val.split('/');
(nestedFn = (object) => {
outKey = keys.shift();
object[outKey] = object[outKey] || {};
if (keys.length == 0) object[outKey] = true;
if (keys.length > 0) nestedFn(object[outKey]);
})(Obj)
})
return Obj;
})(input);
console.log(result);
I try with array reduce, hope it help
let input = [
"animal/mammal/dog",
"animal/mammal/cat/tiger",
"animal/mammal/cat/lion",
"animal/elephant",
"animal/reptile",
"plant/sunflower",
];
let convertInput = (i = []) =>
i.reduce((prev, currItem = "") => {
let pointer = prev;
currItem.split("/").reduce((prevPre, currPre, preIdx, arrPre) => {
if (!pointer[currPre]) {
pointer[currPre] = preIdx === arrPre.length - 1 ? true : {};
}
pointer = pointer[currPre];
}, {});
return prev;
}, {});
console.log(JSON.stringify(convertInput(input), null, 4));
I have array like this:
var arr = [
{"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
{"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
]
And I want to make a new array look like this:
[
{
"type": "color",
"relation":[{"pid": "ITEM_1", "id": "ITEM_1_1"},
{"pid": "ITEM_2", "id": "ITEM_2_2"}]
}, {
"type": "size",
"relation":[{"pid": "DEFAULT_0", "id": ["DEFAULT_0_1","DEFAULT_0_2"]}]
}
]
Thanks.
=========================================
Thanks Abrar's answer. I adjust it slightly for grouping the same pid items and get the result I want. But there should be a better way to do this?
const arr = [
{"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
{"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
];
const resultArr = [];
const groups =[];
arr.forEach((data) => {
let type = data.type;
let newArr = arr.filter(el => el.type === type);
let resObj = {
"type": type,
"relation": []
};
newArr.forEach(el => {
groups.push({"pid": el.pid, "id": el.id});
});
var group_to_values = groups.reduce(function(obj, item) {
obj[item.pid] = obj[item.pid] || [];
obj[item.pid].push(item.id);
return obj;
}, {});
resObj.relation.push(group_to_values);
if (resultArr.map(e => e.type).indexOf(type) < 0) {
resultArr.push(resObj);
}
})
console.log(resultArr);
I have refactored your code and now it looks like this -
const arr = [
{"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
{"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
];
const resultArr = [];
arr.forEach((data) => {
let type = data.type;
let newArr = arr.filter(el => el.type === type);
let resObj = {
"type": type,
"relation": []
};
newArr.forEach(el => {
resObj.relation.push({"pid": el.pid, "id": el.id});
});
if (resultArr.map(e => e.type).indexOf(type) < 0) {
resultArr.push(resObj);
}
})
console.log(resultArr); //resultArr contains your desired output
Basically I have filtered out the keys from the array based on the type since that has to be unique (as per your desired output). This should be pretty straightforward and won't require frameworks or even jQuery.
I have an array like bellow each index contains different set of objects,I want to create an uniformal data where object missing in each index will with Value:0 ,
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
]
];
how can I get an array like bellow using above above array
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
{axis:"Sending Money",value:0,id:6},
{axis:"Other",value:0,id:7},
],
[
{axis:"Email",value:0,id:1},
{axis:"Social Networks",value:0,id:2},
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
]
];
There are two functions:
getAllEntries that find all objects and stores them into a variable accEntries. Then accEntries is used to search for all occurrences in a sub-array of d. This whole process is done in checkArray.
checkArray is used to fetch all found and not-found entries in d. Both Arrays (found and not-found) are then used to build a new sub-array that contains either found entries with certain values and/or not-found entries with values of 0.
Hope this helps:
var d = [
[
{
axis: 'Email',
value: 59,
id: 1
},
{
axis: 'Social Networks',
value: 56,
id: 2
},
],
[
{
axis: 'Sending Money',
value: 18,
id: 6
},
{
axis: 'Other',
value: 15,
id: 7
},
]
];
function getAllEntries(array) {
var uniqueEntries = [];
array.forEach(function (subarray) {
subarray.forEach(function (obj) {
if (uniqueEntries.indexOf(obj) === - 1) uniqueEntries.push(obj);
});
});
return uniqueEntries;
}
function checkArray(array, acceptedEntries) {
var result = [];
array.forEach(function (subArray) {
var subResult = [];
var foundEntries = [];
subArray.forEach(function (obj) {
if (foundEntries.indexOf(obj.axis) === - 1) foundEntries.push(obj.axis);
});
var notFound = acceptedEntries.filter(function (accepted) {
return foundEntries.indexOf(accepted.axis) === - 1;
});
foundEntries.forEach(function (found) {
subArray.forEach(function (obj) {
if (obj.axis === found) subResult.push(obj);
});
});
notFound.forEach(function (notfound, index) {
subResult.push({
axis: notfound.axis,
value: 0,
id: notfound.id
});
});
result.push(subResult);
});
return result;
}
var accEntries = getAllEntries(d);
var result = checkArray(d, accEntries);
console.log(result);
You can loop over the array to find all the unique objects and then again loop over to push the values that are not present comparing with the array of objects of unique keys.
You can use ES6 syntax to find if an object with an attribute is present like uniKeys.findIndex(obj => obj.axis === val.axis); and the to push with a zero value use the spread syntax like d[index].push({...val, value: 0});
Below is the snippet for the implementation
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
{axis:"Social Networks",value:89,id:2},
]
];
var uniKeys = [];
$.each(d, function(index, item) {
$.each(item, function(idx, val){
const pos = uniKeys.findIndex(obj => obj.axis === val.axis);
if(pos == - 1) {
uniKeys.push(val);
}
})
})
$.each(d, function(index, item) {
var temp = [];
$.each(uniKeys, function(idx, val){
const pos = item.findIndex(obj => obj.axis === val.axis);
if(pos == - 1) {
d[index].push({...val, value: 0});
}
})
})
console.log(d);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How about a short shallowCopy function (Object.assign is not available in IE) and otherwise less than 10 new lines of code?
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2}
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7}
]
];
var newD_0 = [shallowCopy(d[0][0]), shallowCopy(d[0][1]), shallowCopy(d[1][0]), shallowCopy(d[1][1])];
var newD_1 = [shallowCopy(d[0][0]), shallowCopy(d[0][1]), shallowCopy(d[1][0]), shallowCopy(d[1][1])];
newD_0[2].id = 0;
newD_0[3].id = 0;
newD_1[0].id = 0;
newD_1[1].id = 0;
d = [newD_0, newD_1];
function shallowCopy(obj) {
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = obj[key];
}
}
return copy;
}
console.log(JSON.stringify(d));
RESULT:
[
[
{
"axis":"Email",
"value":59,
"id":1
},
{
"axis":"Social Networks",
"value":56,
"id":2
},
{
"axis":"Sending Money",
"value":18,
"id":0
},
{
"axis":"Other",
"value":15,
"id":0
}
],
[
{
"axis":"Email",
"value":59,
"id":0
},
{
"axis":"Social Networks",
"value":56,
"id":0
},
{
"axis":"Sending Money",
"value":18,
"id":6
},
{
"axis":"Other",
"value":15,
"id":7
}
]
]