Given this code:
<script type="text/javascript">
var arr = [];
var names = [{name : 'George'}, {name : 'Ringo'}, {name : 'Paul'}, {name : 'John'}];
var surnames = [{surname : 'Harrison'}, {surname : 'Starr'}, {surname : 'McCartney'}, {surname : 'Lennon'}];
for (i = 0; i < names.length; i++) {
arr['firstname'] = names[i];
for (j = 0; j < surnames.length; j++) {
arr['firstname']['surname'] = surnames[j];
arr['firstname']['surname']['index'] = i;
console.log(arr);
}
}
</script>
When run, output in the inner loop would only show the last value of surnames array(Lennon) and i(3) on all entries. Output I want to achieve is for each name, surnames will be distributed to all firstnames (eg. John Harrison, John Starr, etc.) and index(i) will increment from 0 to 3. Thanks.
3 Answers 3
Do you want something like this?
var arr = [];
var names = [{
name: 'George'
}, {
name: 'Ringo'
}, {
name: 'Paul'
}, {
name: 'John'
}];
var surnames = [{
surname: 'Harrison'
}, {
surname: 'Starr'
}, {
surname: 'McCartney'
}, {
surname: 'Lennon'
}];
for (i = 0; i < names.length; i++) {
arr.push({
index: i,
firstname: names[i].name,
surname: surnames[i].surname
});
}
console.log(arr);
Sign up to request clarification or add additional context in comments.
Comments
Try like this ,
for (i = 0; i < names.length; i++) {
var obj = new Object;
obj['name'] = names[i];
obj['name']['surname'] = surnames[i].surname;
obj['index'] = i;
arr.push(obj);
}
console.log(arr);
answered Jun 17, 2016 at 10:01
rejo
3,3405 gold badges29 silver badges35 bronze badges
1 Comment
Rayon
arr['firstname'] is not an object to have a key!Looks like you want Cartesian product of all first names with surnames.
try this
var arr = [];
var names = [{
name: 'George'
}, {
name: 'Ringo'
}, {
name: 'Paul'
}, {
name: 'John'
}];
var surnames = [{
surname: 'Harrison'
}, {
surname: 'Starr'
}, {
surname: 'McCartney'
}, {
surname: 'Lennon'
}];
for (i = 0; i < names.length; i++)
{
for (j = 0; j < surnames.length; j++)
{
var tmpObj = JSON.parse(JSON.stringify(names[i]));
tmpObj['surname'] = surnames[j].surname;
tmpObj['index'] = i;
arr.push(tmpObj);
}
}
console.log(arr);
Alternatively you can also do
Object.create(names[i])
instead of
JSON.parse(JSON.stringify(names[i]));
answered Jun 17, 2016 at 10:02
gurvinder372
68.6k11 gold badges78 silver badges98 bronze badges
4 Comments
Craicerjack
did you check your own code. Youre adding all combos of name and surname together.
gurvinder372
@Craicerjack yes, that is what I though OP asked for.
gurvinder372
@Craicerjack OP said
surnames will be distributed to all firstnames Lhan Samson
Exactly the output I wanted. Thanks!
lang-js
arr['firstname']as it is.