Answer the question
In order to leave comments, you need to log in
What are the anomalies with arrays in JS?
Hello.
I've been scratching my head with such an anomaly in JS for half a day.
I have the original array:
arr[arr.length] = {
"id": 22,
"category": 34,
"name": "Jel",
"movie": "Avatar"
};
arr[arr.length] = {
"id": 34,
"category": 12,
"name": "Sali",
"movie": "Ted 2"
};
arr[arr.length] = {
"id": 33,
"category": 34,
"name": "Chesko",
"movie": "Avatar"
};
arr[arr.length] = {
"id": 22,
"category": 34,
"name": "Donny",
"movie": "Avatar"
};
[{
"id": 22,
"movie": "Avatar",
"actors": [{
"category": 34,
"name": "Jet"
}, {
"category": 34,
"name": "Donny"
}]
},
{
"id": 34,
"movie": "Ted 2",
"actors": [{
"category": 12,
"name": "Sali"
}]
},
{
"id": 33,
"movie": "Avatar",
"actors": [{
"category": 34,
"name": "Chesko"
}]
}]
var arr = [],
movies = [];
arr[arr.length] = {
"id": 22,
"category": 34,
"name": "Jel",
"movie": "Avatar"
};
arr[arr.length] = {
"id": 34,
"category": 12,
"name": "Sali",
"movie": "Ted 2"
};
arr[arr.length] = {
"id": 33,
"category": 34,
"name": "Chesko",
"movie": "Avatar"
};
arr[arr.length] = {
"id": 22,
"category": 34,
"name": "Donny",
"movie": "Avatar"
};
for (var i = 0; i < arr.length; i++) {
var id = arr[i].id + '_' + arr[i].movie;
movies[id] = {
"id": arr[i].id,
"movie": arr[i].movie
}
if (!movies[id].actors) movies[id].actors = []
movies[id].actors[movies[id].actors.length] = {
"category": arr[i].category,
"name": arr[i].name,
}
}
console.log(movies);
Answer the question
In order to leave comments, you need to log in
1) Не добавляйте элемент в массив через index, используйте #push
2) Проверяйте на существование переменной, вы каждый раз затираете movies[id]
;
3) Если вы используете конструкцию for (var i = 0; i < arr.length; i++) { }
, то не вызывайте каждый раз length. Делайте так:
var arr = [],
movies = {};
arr.push({
"id": 22,
"category": 34,
"name": "Jel",
"movie": "Avatar"
});
arr.push({
"id": 34,
"category": 12,
"name": "Sali",
"movie": "Ted 2"
});
arr.push({
"id": 33,
"category": 34,
"name": "Chesko",
"movie": "Avatar"
});
arr.push({
"id": 22,
"category": 34,
"name": "Donny",
"movie": "Avatar"
});
movies = arr.reduce(function(res, item){
var id = item.id + "_" + item.movie;
res[ id ] = res[ id ] || {
"id": item.id,
"movie": item.movie,
};
res[id].actors = res[id].actors || [];
res[id].actors.push({
"category": item.category,
"name": item.name,
});
return res;
}, movies);
console.log(movies);
Так?
var newArr = arr.map(function(a){
a.actors = [{
category: a.category,
name: a.name
}];
delete a.category;
delete a.name;
return a;
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question