I am trying to push a value from a key that exists in the first array. This array consists of a country_users array that I have looped through every users array within this one and pushed these to a new array called users
In this demo I am trying to push country from country_users to every user object in the users array.
I am using Vue.js for this purpose, it might be easier with Vue? Any suggestions?
var users = [];
var country_users = [
{
"country": "United States",
"users": [
{
"name": "John"
},
{
"name": "Jane"
},
],
},
{
"country": "Norway",
"users": [
{
"name": "Ola"
},
{
"name": "Jens"
},
],
},
];
// Here I push all users from country_users into a new array called users
for (let cu = 0; cu < country_users.length; cu++) {
for (let u = 0; u < country_users[cu].users.length; u++) {
users.push(country_users[cu].users[u]);
}
// Do I make a new for loop here to push the country into every object inside users array? How?
}
console.log(users);
I want to push the country from the array where the users belonged previously.
The result I want is an array like this for users
var users = [
{
"name": "John",
"country": "United States"
},
{
"name": "Jane",
"country": "United States"
},
{
"name": "Ola",
"country": "Norway"
},
{
"name": "Jens",
"country": "Norway"
}
];
console.log(users);
SOLUTION
var users = [];
var country_users = [
{
"country": "United States",
"users": [
{
"name": "John"
},
{
"name": "Jane"
},
],
},
{
"country": "Norway",
"users": [
{
"name": "Ola"
},
{
"name": "Jens"
},
],
},
];
country_users.forEach((country_user) => {
country_user.users.forEach((user) => {
user.country = country_user.country;
users.push(user);
});
});
console.log(users);