Home > Software engineering >  Merging 2 arrays, with specified items
Merging 2 arrays, with specified items

Time:09-23

I stuck with joining 2 arrays. I fetch data from 2 API, in response I got 2 different arrays, what I want to achive is one array with joined and selected arguments.

const skills = ref([]);
const entries = axios.get(`https://cdn.contentful.com/spaces/${space_id}/environments/${environment_id}/entries?access_token=${access_token}`);
const assets = axios.get(`https://cdn.contentful.com/spaces/${space_id}/environments/${environment_id}/assets?access_token=${access_token}`);
axios
  .all([entries, assets])
  .then(
    axios.spread((...responses) => {
      const responseEntries = responses[0].data.items.map(
        (item) => item.fields
      );
      const responseAssets = responses[1].data.items.map(
        (item) => "https:"   item.fields.file.url
      );
      const checkEntries = Array.isArray(responseEntries);
      const checkAssets = Array.isArray(responseAssets);
      console.log(checkEntries);
      console.log(checkAssets);
      console.log(responseEntries);
      console.log(responseAssets);

      for (let i = 0; i < responseEntries.length; i  ) {
        skills[i].value = [
          responseAssets[i],
          responseEntries[i].title,
          responseEntries[i].list,
          responseEntries[i].description,
        ];
      }
    })
  )
  .catch((error) => console.log(error));

I'm getting error:

TypeError: Cannot set properties of undefined (setting 'value')

Here is what I got in console, and the how arrays looks

CodePudding user response:

Thank you! Your answer help me to rethink that problem and finally I solved it in different way I added a value to first array.

      for (let i = 0; i < responseEntries.length; i  ) {
        responseEntries[i].url = responseAssets[i];
      }
      skills.value = responseEntries;

CodePudding user response:

Your problem is certainly inside the for loop, where you try:

skills[i].value = [...]

at that point, skills[i] doesn't exist so you have to initialize it before into an object, so:

for (let i = 0; i < responseEntries.length; i  ) {
        skills.value[i] = {}
        skills.value[i] = [
          responseAssets[i],
          responseEntries[i].title,
          responseEntries[i].list,
          responseEntries[i].description,
        ];
      }

I still don't understand the first line, though, const skills = ref([]); where, imho, should just be const skills = []

  • Related