Well I know im doing wrong ...
var recipient=[{}];
if (content.moderators.length != 0) {
for (var i = 0; i < content.moderators.length; i++) {
console.log(content.moderators[i])
recipient[i].id=content.moderators[i];
recipient[i].status="unread";
}
}
I’m getting an error :
TypeError: Cannot set property 'id' of undefined
What’s the correct way ...
-
what exactly are you trying to do?Fanyo SILIADIN– Fanyo SILIADIN2017年01月25日 15:14:18 +00:00Commented Jan 25, 2017 at 15:14
5 Answers 5
Define a simple array [] then create object and push it to the array like :
recipient[i]= {'id':content.moderators[i], 'status': 'unread'};
Full code :
var recipient=[];
if (content.moderators.length != 0) {
for (var i = 0; i < content.moderators.length; i++) {
recipient[i]= {'id':content.moderators[i], 'status': 'unread'};
}
}
Hope this helps.
Comments
This should get it:
var recipient = [];
if (content.moderators.length != 0) {
for (var i = 0; i < content.moderators.length; i++) {
console.log(content.moderators[i])
recipient.push({
id: content.moderators[i],
status: "unread"
});
}
}
1 Comment
Try it this way. You need to create the object at recipient[id] before assigning id to it. Here, you'll create the object with the properties populated already
var recipient = [];
if (content.moderators.length != 0) {
for (var i = 0; i < content.moderators.length; i++) {
recipient[i] = {
id: content.moderators[i],
status: "unread"
}
}
}
1 Comment
You could map the new object with Array#map.
The
map()method creates a new array with the results of calling a provided function on every element in this array.
var content = { moderators: ['Hank', 'Jane', 'Ann', 'Bill'] },
recipient = content.moderators.map(function(m) {
return { id: m, status: "unread" };
});
console.log(recipient);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6
var content = { moderators: ['Hank', 'Jane', 'Ann', 'Bill'] },
recipient = content.moderators.map(m => ({ id: m, status: "unread" }));
console.log(recipient);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
if content.moderators is an Array
var recipient = moderators.map(id => ({ id, status: "unread" }))