how to assign object in object











up vote
1
down vote

favorite












how to assign the object in object and filter the value which pass and fail;



the input is:



    [
{
name: 'John',
score: 90,
time: 'evening'
},
{
name: 'Doni',
score: 68,
time: 'morning'
},
{
name: 'Jiu',
score: 50,
time: 'evening'
},
{
name: 'Shin',
score: 92,
time: 'morning'
},
];


and i want the output like this :



{
"evening": {
"pass": [
{
"name": "John",
"score": 90
}
],
"fail": [
{
"name": "jiu",
"score": 50
}
]
},
"morning": {
"pass": [
{
"name": "Shin",
"score": 92
}
],
"fail": [
{
"name": "Doni",
"score": 68
}
]
}
}


do we need to use Object.assign for this ? and how many loop we use for this ??
i do love to know how to add another string in the object beside that ouput,
thanks










share|improve this question






















  • do we need to use Object.assign for this? Not necessarily. and how many loop we use for this? You do not want to know how many loops you need, let the code handle that for you.
    – Abana Clara
    Nov 20 at 0:25










  • yepp, do u know how ?
    – Zr Classic
    Nov 20 at 0:26















up vote
1
down vote

favorite












how to assign the object in object and filter the value which pass and fail;



the input is:



    [
{
name: 'John',
score: 90,
time: 'evening'
},
{
name: 'Doni',
score: 68,
time: 'morning'
},
{
name: 'Jiu',
score: 50,
time: 'evening'
},
{
name: 'Shin',
score: 92,
time: 'morning'
},
];


and i want the output like this :



{
"evening": {
"pass": [
{
"name": "John",
"score": 90
}
],
"fail": [
{
"name": "jiu",
"score": 50
}
]
},
"morning": {
"pass": [
{
"name": "Shin",
"score": 92
}
],
"fail": [
{
"name": "Doni",
"score": 68
}
]
}
}


do we need to use Object.assign for this ? and how many loop we use for this ??
i do love to know how to add another string in the object beside that ouput,
thanks










share|improve this question






















  • do we need to use Object.assign for this? Not necessarily. and how many loop we use for this? You do not want to know how many loops you need, let the code handle that for you.
    – Abana Clara
    Nov 20 at 0:25










  • yepp, do u know how ?
    – Zr Classic
    Nov 20 at 0:26













up vote
1
down vote

favorite









up vote
1
down vote

favorite











how to assign the object in object and filter the value which pass and fail;



the input is:



    [
{
name: 'John',
score: 90,
time: 'evening'
},
{
name: 'Doni',
score: 68,
time: 'morning'
},
{
name: 'Jiu',
score: 50,
time: 'evening'
},
{
name: 'Shin',
score: 92,
time: 'morning'
},
];


and i want the output like this :



{
"evening": {
"pass": [
{
"name": "John",
"score": 90
}
],
"fail": [
{
"name": "jiu",
"score": 50
}
]
},
"morning": {
"pass": [
{
"name": "Shin",
"score": 92
}
],
"fail": [
{
"name": "Doni",
"score": 68
}
]
}
}


do we need to use Object.assign for this ? and how many loop we use for this ??
i do love to know how to add another string in the object beside that ouput,
thanks










share|improve this question













how to assign the object in object and filter the value which pass and fail;



the input is:



    [
{
name: 'John',
score: 90,
time: 'evening'
},
{
name: 'Doni',
score: 68,
time: 'morning'
},
{
name: 'Jiu',
score: 50,
time: 'evening'
},
{
name: 'Shin',
score: 92,
time: 'morning'
},
];


and i want the output like this :



{
"evening": {
"pass": [
{
"name": "John",
"score": 90
}
],
"fail": [
{
"name": "jiu",
"score": 50
}
]
},
"morning": {
"pass": [
{
"name": "Shin",
"score": 92
}
],
"fail": [
{
"name": "Doni",
"score": 68
}
]
}
}


do we need to use Object.assign for this ? and how many loop we use for this ??
i do love to know how to add another string in the object beside that ouput,
thanks







javascript arrays object iterator






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 0:20









Zr Classic

676




676












  • do we need to use Object.assign for this? Not necessarily. and how many loop we use for this? You do not want to know how many loops you need, let the code handle that for you.
    – Abana Clara
    Nov 20 at 0:25










  • yepp, do u know how ?
    – Zr Classic
    Nov 20 at 0:26


















  • do we need to use Object.assign for this? Not necessarily. and how many loop we use for this? You do not want to know how many loops you need, let the code handle that for you.
    – Abana Clara
    Nov 20 at 0:25










  • yepp, do u know how ?
    – Zr Classic
    Nov 20 at 0:26
















do we need to use Object.assign for this? Not necessarily. and how many loop we use for this? You do not want to know how many loops you need, let the code handle that for you.
– Abana Clara
Nov 20 at 0:25




do we need to use Object.assign for this? Not necessarily. and how many loop we use for this? You do not want to know how many loops you need, let the code handle that for you.
– Abana Clara
Nov 20 at 0:25












yepp, do u know how ?
– Zr Classic
Nov 20 at 0:26




yepp, do u know how ?
– Zr Classic
Nov 20 at 0:26












3 Answers
3






active

oldest

votes

















up vote
2
down vote



accepted










You can do something like this:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const grp = (d, p) => d.reduce((r,c) => (r[c[p]] = [...r[c[p]] || , c], r), {})
const grpV = (d, rng) => d.reduce((r,{name, score}) => {
let key = score > rng ? 'pass' : 'fail'
r[key] = [...r[key] || , {name, score}]
return r
}, {})

const r = Object.entries(grp(data, 'time')).map(([k,v]) => ({[k]: grpV(v, 75)}))

console.log(r)





The idea is the group 2 times one on the time and 2nd on the score.



grp: function to group by a property (in this case 'time') which returns an object with 2 properties: evening and morning each of which is an array containing the classes.



grpV: function to group by value (in this case 75) which returns an object with 2 properties: pass and fail each of which is an array containing the classes.



On the end once we have those tools we are saying ... give me the entries of the grouped by time object and for each of the groups ... group by score.



Here how something like this could look like if we ware using lodash:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const partition = (x, p) => _(x)
.partition(y => y.score > p)
.map((x,i) => ({ [i==0 ? 'pass': 'fail']: _.omit(x[0], 'time')}))
.value()

const r = _(data)
.groupBy('time')
.mapValues(x => partition(x, 75))
.value()

console.log(r)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





Adding it as an example since it does help with readability of what the ES6 example is doing to some extend.






share|improve this answer























  • hmmm it seems difficult for newbie to understand those syntax
    – Zr Classic
    Nov 20 at 10:17


















up vote
3
down vote













There's a lot of ways to do this. The simplest is probably to make a base object that represent your empty results. Then loop over the students and fill the arrays:






let students = [{name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

// Empty case
let base = {
"evening": {"pass": , "fail": },
"morning": {"pass": , "fail": }
}

const PASSING = 70

students.forEach(({name, score, time}) => {
let key = score >= PASSING ? 'pass' : 'fail'
base[time][key].push({name, score})
})
console.log(base)





This makes is easy to have empty arrays, which is probably what you want if there are no students in a particular category.



EDIT based on comment:



To support arbitrary times, you can just create the times on the object as you find them. reduce() is good for this, but you could also use a regular loop. For example with an added afternoon time:






let students = [{name: 'Mark',score: 95,time: 'afternoon'}, {name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

const PASSING = 70

let result = students.reduce((obj, {name, score, time}) => {
if (!obj[time]) obj[time] = {'pass': , 'fail': }

let key = score >= PASSING ? 'pass' : 'fail'
obj[time][key].push({name, score})

return obj
}, {})


console.log(result)








share|improve this answer























  • how about if we other times, midnight, noon? should we create it on base variable? can u use that by function
    – Zr Classic
    Nov 20 at 1:27










  • @ZrClassic If you are going to have arbitrary time categories, you will be better off building the object as you go. That will be a more general solution, but also more complicated.
    – Mark Meyer
    Nov 20 at 1:29


















up vote
1
down vote













I'm sure there are more elegant ways to do this. But this one is probably one of the simplest beginner-friendly ways you can go about this.



I loop through the input array, check the existence of the .time values as keys on the output object and create the pass and fail keys. Then evaluate the .score against the passingScore and push the necessary data to it.



Should be pretty easy to understand once you see and try the code below:






const data =   [
{name: 'John',score: 90, time: 'evening'},
{name: 'Doni',score: 68, time: 'morning'},
{name: 'Jiu',score: 50, time: 'evening'},
{name: 'Shin',score: 92, time: 'morning'},
{name: 'Fubar',score: 75, time: 'noon'},
];


function formatData(data){
const passingScore = 75;
const output = {};

data.forEach(function(item){
if(!output[item.time]) output[item.time] = {pass: , fail: };

const stud = { name: item.name, score: item.score };

if(item.score >= passingScore) output[item.time]['pass'].push(stud)
else output[item.time]['fail'].push(stud)
});

return output;
}

console.log(formatData(data));








share|improve this answer























  • this is the perfect one for beginner
    – Zr Classic
    Nov 20 at 4:29











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384504%2fhow-to-assign-object-in-object%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










You can do something like this:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const grp = (d, p) => d.reduce((r,c) => (r[c[p]] = [...r[c[p]] || , c], r), {})
const grpV = (d, rng) => d.reduce((r,{name, score}) => {
let key = score > rng ? 'pass' : 'fail'
r[key] = [...r[key] || , {name, score}]
return r
}, {})

const r = Object.entries(grp(data, 'time')).map(([k,v]) => ({[k]: grpV(v, 75)}))

console.log(r)





The idea is the group 2 times one on the time and 2nd on the score.



grp: function to group by a property (in this case 'time') which returns an object with 2 properties: evening and morning each of which is an array containing the classes.



grpV: function to group by value (in this case 75) which returns an object with 2 properties: pass and fail each of which is an array containing the classes.



On the end once we have those tools we are saying ... give me the entries of the grouped by time object and for each of the groups ... group by score.



Here how something like this could look like if we ware using lodash:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const partition = (x, p) => _(x)
.partition(y => y.score > p)
.map((x,i) => ({ [i==0 ? 'pass': 'fail']: _.omit(x[0], 'time')}))
.value()

const r = _(data)
.groupBy('time')
.mapValues(x => partition(x, 75))
.value()

console.log(r)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





Adding it as an example since it does help with readability of what the ES6 example is doing to some extend.






share|improve this answer























  • hmmm it seems difficult for newbie to understand those syntax
    – Zr Classic
    Nov 20 at 10:17















up vote
2
down vote



accepted










You can do something like this:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const grp = (d, p) => d.reduce((r,c) => (r[c[p]] = [...r[c[p]] || , c], r), {})
const grpV = (d, rng) => d.reduce((r,{name, score}) => {
let key = score > rng ? 'pass' : 'fail'
r[key] = [...r[key] || , {name, score}]
return r
}, {})

const r = Object.entries(grp(data, 'time')).map(([k,v]) => ({[k]: grpV(v, 75)}))

console.log(r)





The idea is the group 2 times one on the time and 2nd on the score.



grp: function to group by a property (in this case 'time') which returns an object with 2 properties: evening and morning each of which is an array containing the classes.



grpV: function to group by value (in this case 75) which returns an object with 2 properties: pass and fail each of which is an array containing the classes.



On the end once we have those tools we are saying ... give me the entries of the grouped by time object and for each of the groups ... group by score.



Here how something like this could look like if we ware using lodash:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const partition = (x, p) => _(x)
.partition(y => y.score > p)
.map((x,i) => ({ [i==0 ? 'pass': 'fail']: _.omit(x[0], 'time')}))
.value()

const r = _(data)
.groupBy('time')
.mapValues(x => partition(x, 75))
.value()

console.log(r)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





Adding it as an example since it does help with readability of what the ES6 example is doing to some extend.






share|improve this answer























  • hmmm it seems difficult for newbie to understand those syntax
    – Zr Classic
    Nov 20 at 10:17













up vote
2
down vote



accepted







up vote
2
down vote



accepted






You can do something like this:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const grp = (d, p) => d.reduce((r,c) => (r[c[p]] = [...r[c[p]] || , c], r), {})
const grpV = (d, rng) => d.reduce((r,{name, score}) => {
let key = score > rng ? 'pass' : 'fail'
r[key] = [...r[key] || , {name, score}]
return r
}, {})

const r = Object.entries(grp(data, 'time')).map(([k,v]) => ({[k]: grpV(v, 75)}))

console.log(r)





The idea is the group 2 times one on the time and 2nd on the score.



grp: function to group by a property (in this case 'time') which returns an object with 2 properties: evening and morning each of which is an array containing the classes.



grpV: function to group by value (in this case 75) which returns an object with 2 properties: pass and fail each of which is an array containing the classes.



On the end once we have those tools we are saying ... give me the entries of the grouped by time object and for each of the groups ... group by score.



Here how something like this could look like if we ware using lodash:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const partition = (x, p) => _(x)
.partition(y => y.score > p)
.map((x,i) => ({ [i==0 ? 'pass': 'fail']: _.omit(x[0], 'time')}))
.value()

const r = _(data)
.groupBy('time')
.mapValues(x => partition(x, 75))
.value()

console.log(r)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





Adding it as an example since it does help with readability of what the ES6 example is doing to some extend.






share|improve this answer














You can do something like this:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const grp = (d, p) => d.reduce((r,c) => (r[c[p]] = [...r[c[p]] || , c], r), {})
const grpV = (d, rng) => d.reduce((r,{name, score}) => {
let key = score > rng ? 'pass' : 'fail'
r[key] = [...r[key] || , {name, score}]
return r
}, {})

const r = Object.entries(grp(data, 'time')).map(([k,v]) => ({[k]: grpV(v, 75)}))

console.log(r)





The idea is the group 2 times one on the time and 2nd on the score.



grp: function to group by a property (in this case 'time') which returns an object with 2 properties: evening and morning each of which is an array containing the classes.



grpV: function to group by value (in this case 75) which returns an object with 2 properties: pass and fail each of which is an array containing the classes.



On the end once we have those tools we are saying ... give me the entries of the grouped by time object and for each of the groups ... group by score.



Here how something like this could look like if we ware using lodash:






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const partition = (x, p) => _(x)
.partition(y => y.score > p)
.map((x,i) => ({ [i==0 ? 'pass': 'fail']: _.omit(x[0], 'time')}))
.value()

const r = _(data)
.groupBy('time')
.mapValues(x => partition(x, 75))
.value()

console.log(r)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





Adding it as an example since it does help with readability of what the ES6 example is doing to some extend.






const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const grp = (d, p) => d.reduce((r,c) => (r[c[p]] = [...r[c[p]] || , c], r), {})
const grpV = (d, rng) => d.reduce((r,{name, score}) => {
let key = score > rng ? 'pass' : 'fail'
r[key] = [...r[key] || , {name, score}]
return r
}, {})

const r = Object.entries(grp(data, 'time')).map(([k,v]) => ({[k]: grpV(v, 75)}))

console.log(r)





const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const grp = (d, p) => d.reduce((r,c) => (r[c[p]] = [...r[c[p]] || , c], r), {})
const grpV = (d, rng) => d.reduce((r,{name, score}) => {
let key = score > rng ? 'pass' : 'fail'
r[key] = [...r[key] || , {name, score}]
return r
}, {})

const r = Object.entries(grp(data, 'time')).map(([k,v]) => ({[k]: grpV(v, 75)}))

console.log(r)





const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const partition = (x, p) => _(x)
.partition(y => y.score > p)
.map((x,i) => ({ [i==0 ? 'pass': 'fail']: _.omit(x[0], 'time')}))
.value()

const r = _(data)
.groupBy('time')
.mapValues(x => partition(x, 75))
.value()

console.log(r)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





const data = [{ name: 'John', score: 90, time: 'evening' }, { name: 'Doni', score: 68, time: 'morning' }, { name: 'Jiu', score: 50, time: 'evening' }, { name: 'Shin', score: 92, time: 'morning' }, ];

const partition = (x, p) => _(x)
.partition(y => y.score > p)
.map((x,i) => ({ [i==0 ? 'pass': 'fail']: _.omit(x[0], 'time')}))
.value()

const r = _(data)
.groupBy('time')
.mapValues(x => partition(x, 75))
.value()

console.log(r)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 at 1:43

























answered Nov 20 at 0:43









Akrion

9,19411224




9,19411224












  • hmmm it seems difficult for newbie to understand those syntax
    – Zr Classic
    Nov 20 at 10:17


















  • hmmm it seems difficult for newbie to understand those syntax
    – Zr Classic
    Nov 20 at 10:17
















hmmm it seems difficult for newbie to understand those syntax
– Zr Classic
Nov 20 at 10:17




hmmm it seems difficult for newbie to understand those syntax
– Zr Classic
Nov 20 at 10:17












up vote
3
down vote













There's a lot of ways to do this. The simplest is probably to make a base object that represent your empty results. Then loop over the students and fill the arrays:






let students = [{name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

// Empty case
let base = {
"evening": {"pass": , "fail": },
"morning": {"pass": , "fail": }
}

const PASSING = 70

students.forEach(({name, score, time}) => {
let key = score >= PASSING ? 'pass' : 'fail'
base[time][key].push({name, score})
})
console.log(base)





This makes is easy to have empty arrays, which is probably what you want if there are no students in a particular category.



EDIT based on comment:



To support arbitrary times, you can just create the times on the object as you find them. reduce() is good for this, but you could also use a regular loop. For example with an added afternoon time:






let students = [{name: 'Mark',score: 95,time: 'afternoon'}, {name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

const PASSING = 70

let result = students.reduce((obj, {name, score, time}) => {
if (!obj[time]) obj[time] = {'pass': , 'fail': }

let key = score >= PASSING ? 'pass' : 'fail'
obj[time][key].push({name, score})

return obj
}, {})


console.log(result)








share|improve this answer























  • how about if we other times, midnight, noon? should we create it on base variable? can u use that by function
    – Zr Classic
    Nov 20 at 1:27










  • @ZrClassic If you are going to have arbitrary time categories, you will be better off building the object as you go. That will be a more general solution, but also more complicated.
    – Mark Meyer
    Nov 20 at 1:29















up vote
3
down vote













There's a lot of ways to do this. The simplest is probably to make a base object that represent your empty results. Then loop over the students and fill the arrays:






let students = [{name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

// Empty case
let base = {
"evening": {"pass": , "fail": },
"morning": {"pass": , "fail": }
}

const PASSING = 70

students.forEach(({name, score, time}) => {
let key = score >= PASSING ? 'pass' : 'fail'
base[time][key].push({name, score})
})
console.log(base)





This makes is easy to have empty arrays, which is probably what you want if there are no students in a particular category.



EDIT based on comment:



To support arbitrary times, you can just create the times on the object as you find them. reduce() is good for this, but you could also use a regular loop. For example with an added afternoon time:






let students = [{name: 'Mark',score: 95,time: 'afternoon'}, {name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

const PASSING = 70

let result = students.reduce((obj, {name, score, time}) => {
if (!obj[time]) obj[time] = {'pass': , 'fail': }

let key = score >= PASSING ? 'pass' : 'fail'
obj[time][key].push({name, score})

return obj
}, {})


console.log(result)








share|improve this answer























  • how about if we other times, midnight, noon? should we create it on base variable? can u use that by function
    – Zr Classic
    Nov 20 at 1:27










  • @ZrClassic If you are going to have arbitrary time categories, you will be better off building the object as you go. That will be a more general solution, but also more complicated.
    – Mark Meyer
    Nov 20 at 1:29













up vote
3
down vote










up vote
3
down vote









There's a lot of ways to do this. The simplest is probably to make a base object that represent your empty results. Then loop over the students and fill the arrays:






let students = [{name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

// Empty case
let base = {
"evening": {"pass": , "fail": },
"morning": {"pass": , "fail": }
}

const PASSING = 70

students.forEach(({name, score, time}) => {
let key = score >= PASSING ? 'pass' : 'fail'
base[time][key].push({name, score})
})
console.log(base)





This makes is easy to have empty arrays, which is probably what you want if there are no students in a particular category.



EDIT based on comment:



To support arbitrary times, you can just create the times on the object as you find them. reduce() is good for this, but you could also use a regular loop. For example with an added afternoon time:






let students = [{name: 'Mark',score: 95,time: 'afternoon'}, {name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

const PASSING = 70

let result = students.reduce((obj, {name, score, time}) => {
if (!obj[time]) obj[time] = {'pass': , 'fail': }

let key = score >= PASSING ? 'pass' : 'fail'
obj[time][key].push({name, score})

return obj
}, {})


console.log(result)








share|improve this answer














There's a lot of ways to do this. The simplest is probably to make a base object that represent your empty results. Then loop over the students and fill the arrays:






let students = [{name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

// Empty case
let base = {
"evening": {"pass": , "fail": },
"morning": {"pass": , "fail": }
}

const PASSING = 70

students.forEach(({name, score, time}) => {
let key = score >= PASSING ? 'pass' : 'fail'
base[time][key].push({name, score})
})
console.log(base)





This makes is easy to have empty arrays, which is probably what you want if there are no students in a particular category.



EDIT based on comment:



To support arbitrary times, you can just create the times on the object as you find them. reduce() is good for this, but you could also use a regular loop. For example with an added afternoon time:






let students = [{name: 'Mark',score: 95,time: 'afternoon'}, {name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

const PASSING = 70

let result = students.reduce((obj, {name, score, time}) => {
if (!obj[time]) obj[time] = {'pass': , 'fail': }

let key = score >= PASSING ? 'pass' : 'fail'
obj[time][key].push({name, score})

return obj
}, {})


console.log(result)








let students = [{name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

// Empty case
let base = {
"evening": {"pass": , "fail": },
"morning": {"pass": , "fail": }
}

const PASSING = 70

students.forEach(({name, score, time}) => {
let key = score >= PASSING ? 'pass' : 'fail'
base[time][key].push({name, score})
})
console.log(base)





let students = [{name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

// Empty case
let base = {
"evening": {"pass": , "fail": },
"morning": {"pass": , "fail": }
}

const PASSING = 70

students.forEach(({name, score, time}) => {
let key = score >= PASSING ? 'pass' : 'fail'
base[time][key].push({name, score})
})
console.log(base)





let students = [{name: 'Mark',score: 95,time: 'afternoon'}, {name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

const PASSING = 70

let result = students.reduce((obj, {name, score, time}) => {
if (!obj[time]) obj[time] = {'pass': , 'fail': }

let key = score >= PASSING ? 'pass' : 'fail'
obj[time][key].push({name, score})

return obj
}, {})


console.log(result)





let students = [{name: 'Mark',score: 95,time: 'afternoon'}, {name: 'John',score: 90,time: 'evening'},{name: 'Doni',score: 68,time: 'morning'},{name: 'Jiu',score: 50,time: 'evening'},{name: 'Shin',score: 92,time: 'morning'},];

const PASSING = 70

let result = students.reduce((obj, {name, score, time}) => {
if (!obj[time]) obj[time] = {'pass': , 'fail': }

let key = score >= PASSING ? 'pass' : 'fail'
obj[time][key].push({name, score})

return obj
}, {})


console.log(result)






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 at 1:35

























answered Nov 20 at 0:40









Mark Meyer

33.4k32854




33.4k32854












  • how about if we other times, midnight, noon? should we create it on base variable? can u use that by function
    – Zr Classic
    Nov 20 at 1:27










  • @ZrClassic If you are going to have arbitrary time categories, you will be better off building the object as you go. That will be a more general solution, but also more complicated.
    – Mark Meyer
    Nov 20 at 1:29


















  • how about if we other times, midnight, noon? should we create it on base variable? can u use that by function
    – Zr Classic
    Nov 20 at 1:27










  • @ZrClassic If you are going to have arbitrary time categories, you will be better off building the object as you go. That will be a more general solution, but also more complicated.
    – Mark Meyer
    Nov 20 at 1:29
















how about if we other times, midnight, noon? should we create it on base variable? can u use that by function
– Zr Classic
Nov 20 at 1:27




how about if we other times, midnight, noon? should we create it on base variable? can u use that by function
– Zr Classic
Nov 20 at 1:27












@ZrClassic If you are going to have arbitrary time categories, you will be better off building the object as you go. That will be a more general solution, but also more complicated.
– Mark Meyer
Nov 20 at 1:29




@ZrClassic If you are going to have arbitrary time categories, you will be better off building the object as you go. That will be a more general solution, but also more complicated.
– Mark Meyer
Nov 20 at 1:29










up vote
1
down vote













I'm sure there are more elegant ways to do this. But this one is probably one of the simplest beginner-friendly ways you can go about this.



I loop through the input array, check the existence of the .time values as keys on the output object and create the pass and fail keys. Then evaluate the .score against the passingScore and push the necessary data to it.



Should be pretty easy to understand once you see and try the code below:






const data =   [
{name: 'John',score: 90, time: 'evening'},
{name: 'Doni',score: 68, time: 'morning'},
{name: 'Jiu',score: 50, time: 'evening'},
{name: 'Shin',score: 92, time: 'morning'},
{name: 'Fubar',score: 75, time: 'noon'},
];


function formatData(data){
const passingScore = 75;
const output = {};

data.forEach(function(item){
if(!output[item.time]) output[item.time] = {pass: , fail: };

const stud = { name: item.name, score: item.score };

if(item.score >= passingScore) output[item.time]['pass'].push(stud)
else output[item.time]['fail'].push(stud)
});

return output;
}

console.log(formatData(data));








share|improve this answer























  • this is the perfect one for beginner
    – Zr Classic
    Nov 20 at 4:29















up vote
1
down vote













I'm sure there are more elegant ways to do this. But this one is probably one of the simplest beginner-friendly ways you can go about this.



I loop through the input array, check the existence of the .time values as keys on the output object and create the pass and fail keys. Then evaluate the .score against the passingScore and push the necessary data to it.



Should be pretty easy to understand once you see and try the code below:






const data =   [
{name: 'John',score: 90, time: 'evening'},
{name: 'Doni',score: 68, time: 'morning'},
{name: 'Jiu',score: 50, time: 'evening'},
{name: 'Shin',score: 92, time: 'morning'},
{name: 'Fubar',score: 75, time: 'noon'},
];


function formatData(data){
const passingScore = 75;
const output = {};

data.forEach(function(item){
if(!output[item.time]) output[item.time] = {pass: , fail: };

const stud = { name: item.name, score: item.score };

if(item.score >= passingScore) output[item.time]['pass'].push(stud)
else output[item.time]['fail'].push(stud)
});

return output;
}

console.log(formatData(data));








share|improve this answer























  • this is the perfect one for beginner
    – Zr Classic
    Nov 20 at 4:29













up vote
1
down vote










up vote
1
down vote









I'm sure there are more elegant ways to do this. But this one is probably one of the simplest beginner-friendly ways you can go about this.



I loop through the input array, check the existence of the .time values as keys on the output object and create the pass and fail keys. Then evaluate the .score against the passingScore and push the necessary data to it.



Should be pretty easy to understand once you see and try the code below:






const data =   [
{name: 'John',score: 90, time: 'evening'},
{name: 'Doni',score: 68, time: 'morning'},
{name: 'Jiu',score: 50, time: 'evening'},
{name: 'Shin',score: 92, time: 'morning'},
{name: 'Fubar',score: 75, time: 'noon'},
];


function formatData(data){
const passingScore = 75;
const output = {};

data.forEach(function(item){
if(!output[item.time]) output[item.time] = {pass: , fail: };

const stud = { name: item.name, score: item.score };

if(item.score >= passingScore) output[item.time]['pass'].push(stud)
else output[item.time]['fail'].push(stud)
});

return output;
}

console.log(formatData(data));








share|improve this answer














I'm sure there are more elegant ways to do this. But this one is probably one of the simplest beginner-friendly ways you can go about this.



I loop through the input array, check the existence of the .time values as keys on the output object and create the pass and fail keys. Then evaluate the .score against the passingScore and push the necessary data to it.



Should be pretty easy to understand once you see and try the code below:






const data =   [
{name: 'John',score: 90, time: 'evening'},
{name: 'Doni',score: 68, time: 'morning'},
{name: 'Jiu',score: 50, time: 'evening'},
{name: 'Shin',score: 92, time: 'morning'},
{name: 'Fubar',score: 75, time: 'noon'},
];


function formatData(data){
const passingScore = 75;
const output = {};

data.forEach(function(item){
if(!output[item.time]) output[item.time] = {pass: , fail: };

const stud = { name: item.name, score: item.score };

if(item.score >= passingScore) output[item.time]['pass'].push(stud)
else output[item.time]['fail'].push(stud)
});

return output;
}

console.log(formatData(data));








const data =   [
{name: 'John',score: 90, time: 'evening'},
{name: 'Doni',score: 68, time: 'morning'},
{name: 'Jiu',score: 50, time: 'evening'},
{name: 'Shin',score: 92, time: 'morning'},
{name: 'Fubar',score: 75, time: 'noon'},
];


function formatData(data){
const passingScore = 75;
const output = {};

data.forEach(function(item){
if(!output[item.time]) output[item.time] = {pass: , fail: };

const stud = { name: item.name, score: item.score };

if(item.score >= passingScore) output[item.time]['pass'].push(stud)
else output[item.time]['fail'].push(stud)
});

return output;
}

console.log(formatData(data));





const data =   [
{name: 'John',score: 90, time: 'evening'},
{name: 'Doni',score: 68, time: 'morning'},
{name: 'Jiu',score: 50, time: 'evening'},
{name: 'Shin',score: 92, time: 'morning'},
{name: 'Fubar',score: 75, time: 'noon'},
];


function formatData(data){
const passingScore = 75;
const output = {};

data.forEach(function(item){
if(!output[item.time]) output[item.time] = {pass: , fail: };

const stud = { name: item.name, score: item.score };

if(item.score >= passingScore) output[item.time]['pass'].push(stud)
else output[item.time]['fail'].push(stud)
});

return output;
}

console.log(formatData(data));






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 at 4:53

























answered Nov 20 at 0:33









Abana Clara

1,452719




1,452719












  • this is the perfect one for beginner
    – Zr Classic
    Nov 20 at 4:29


















  • this is the perfect one for beginner
    – Zr Classic
    Nov 20 at 4:29
















this is the perfect one for beginner
– Zr Classic
Nov 20 at 4:29




this is the perfect one for beginner
– Zr Classic
Nov 20 at 4:29


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384504%2fhow-to-assign-object-in-object%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Create new schema in PostgreSQL using DBeaver

Deepest pit of an array with Javascript: test on Codility

Costa Masnaga