I was wondering if there is a simple way, a built-in function to split a dictionary in javascript.
For example:
my dictionary is:
let data = { "Is your salary above 1000$?":["yes","no",false,0],
"Is your salary above 2000?":["yes","no",false,1],
"Is your salary above 3000?":["yes","no",false,2],
"Is your salary above 4000?":["yes","no",false,3],
"Is your salary above 5000?":["yes","no",false,4]}
I want it to be:
data1 = { "Is your salary above 1000$?":["yes","no",false,0],
"Is your salary above 2000?":["yes","no",false,1]}
data2 = { "Is your salary above 3000?":["yes","no",false,2],
"Is your salary above 4000?":["yes","no",false,3],
"Is your salary above 5000?":["yes","no",false,4]}
I can do it through looping but i was wondering if there is a faster way or a built in fuction, i did search but i didn't find anything that does that.
CodePudding user response:
- Use Object.entries() to convert your object into an array of key-value pairs
- slice it using Array.prototype.slice()
- Convert back every Array of key-value pairs back into an Object use Object.fromEntries()
const data = {
"Is your salary above 1000$?": ["yes", "no", false, 0],
"Is your salary above 2000$?": ["yes", "no", false, 1],
"Is your salary above 3000$?": ["yes", "no", false, 2],
"Is your salary above 4000$?": ["yes", "no", false, 3],
"Is your salary above 5000$?": ["yes", "no", false, 4],
};
const sliceAt = 2;
const dataArr = Object.entries(data);
const obA = Object.fromEntries(dataArr.slice(0, sliceAt));
const obB = Object.fromEntries(dataArr.slice(sliceAt));
console.log(obA);
console.log(obB);
CodePudding user response:
Use Object.entries
to convert it to an array. Then use splice
to divide it up. Then use Object.fromEntries()
to convert the arrays back into objects.
let data = {
"Is your salary above 1000$?": ["yes", "no", false, 0],
"Is your salary above 2000?": ["yes", "no", false, 1],
"Is your salary above 3000?": ["yes", "no", false, 2],
"Is your salary above 4000?": ["yes", "no", false, 3],
"Is your salary above 5000?": ["yes", "no", false, 4]
}
const end = Object.entries(data);
const start = end.splice(0, 2); // Take two entries off the front of the array
const results = [start, end].map(Object.fromEntries);
console.log(results);