Reputation: 41
I have these arrays:
const characters = [{
Tom: {},
Jerry: {}
}]
const data1 = [{
Species: 'Cat',
Gender: 'Male'
}]
const data2 = [{
Species: 'Mouse',
Gender: 'Male'
}]
The final array should look like this:
const characters = [{
Tom: {
Species: 'Cat',
Gender: 'Male'
},
Jerry: {
Species: 'Mouse',
Gender: 'Male'
},
character3: {
// data3 here
},
character4: {
// data4 here
}
}]
How can I push the data to its position in the main array?
If I have more characters, I will have more data to push, relative to the character.
Upvotes: 0
Views: 87
Reputation: 6119
By definition, a JavaScript object is an unordered collection of zero or more name/value pairs (source 1, source 2). It may work in some cases, but as long as you keep use characters
as an object and not an array, you will likely end up with some unexpected results.
If you switch your approach to using characters
as an array instead, this is quite simple to do. here is how I would do it:
const characters = ["Tom", "Jerry"];
const data1 = {
Species: 'Cat',
Gender: 'Male'
};
const data2 = {
Species: 'Mouse',
Gender: 'Male'
};
const characterAssign = (characters, ...datasets) => Object.fromEntries(characters.slice(0, datasets.length).map((character, i) => [character, datasets[i]]));
const charactersObj = characterAssign(characters, data1, data2);
console.log(charactersObj);
// ➞ {Jerry: {Species: "Mouse", Gender: "Male"}, Tom: {Species: "Cat", Gender: "Male"}}
console.log(charactersObj.Jerry);
// ➞ {Species: "Mouse", Gender: "Male"}
console.log(charactersObj.Tom.Species);
// ➞ "Cat"
The first part of our characterAssign
function slice(0, datasets.length)
ensures that we only work with as many characters as there are datasets passed into the function for. So if you were to pass in an array of ["Tom", "Jerry", "Spike"]
with only two datasets, "Spike" would be excluded from the returned object since there was no dataset provided for him. This is quality assurance.
Next, we map the datasets passed into the function to each character by index value (0,1,…
). This creates an array of arrays for each character. Finally, all of that is computed by the Object.fromEntries
method and converted into an object so characters can be referenced by name in the returned function.
Upvotes: 1
Reputation: 369
First of all take characters keys out of array or dictionary. Using both is useless.
After that you can loop your characters keys and you can set your data as value.
Code:
const characters = {Tom: {}, Jerry: {}};
const multiple_data = [{Species: 'Cat', Gender: 'Male'}, {Species: 'Mouse', Gender: 'Male'}];
for (i = 0; i < Object.keys(characters).length; i++)
{
characters[Object.keys(characters)[i]] = multiple_data[i];
}
console.log(characters);
Output:
[Jerry: {Species: "Mouse", Gender: "Male"}, Tom: {Species: "Cat", Gender: "Male"}]
Upvotes: 0