Home > Back-end >  using array for URLSearchParams in vue3
using array for URLSearchParams in vue3

Time:08-02

i want to append key and value of array , using for axos request here is the array const

schedule = ref({
  "userId" : 13,
  "sunday" : ["mornig","afternoon","nigh"],
  "monday" : ["afternoon","nigh"],
  "wednesday" : ["mornig","afternoon"]
})

to append manuallya i can do like this

params.append("userId",data.value.userId)
params.append("sunday[0]",data.value.sunday[0])
params.append("sunday[1]",data.value.sunday[1])
params.append("sunday[2]",data.value.sunday[2])
params.append("monday[0]",data.value.monday[0])
params.append("monday[1]",data.value.monday[1])
params.append("wednesday[0]",data.value.wednesday[0])
params.append("wednesday[1]",data.value.wednesday[1])

but this will be problim if length of the schedule time l (morning,night ...) unknown i do like this

 let i = 0
    for(let j in data.value){
      console.log(j $[i  ])
    }

and also loop using for in and for of , but none of them are success

CodePudding user response:

You "just" need to do a nested iteration. Loop through object, and if any value is an array, loop through the array. Here's an example code to flatten the dataset. Just note that instead of flattenData(schedule) you'd need to pass the ref's value with flattenData(schedule.value).

const schedule = {
  userId: 13,
  sunday: ["mornig", "afternoon", "nigh"],
  monday: ["afternoon", "nigh"],
  wednesday: ["morning", "afternoon"],
};

function flattenData(data) {
  const o = {};
  Object.keys(data).forEach((dataKey) => {
    if (Array.isArray(data[dataKey])) {
      data[dataKey].forEach(
        (_, nestedArrayIndex) =>
          (o[`${dataKey}[${nestedArrayIndex}]`] =
            data[dataKey][nestedArrayIndex])
      );
    } else {
      o[dataKey] = data[dataKey];
    }
  });
  return o;
}

// show flattened data
console.log(flattenData(schedule));

// prepare params
const params = new URLSearchParams("");

// populate
Object.entries(flattenData(schedule)).forEach(([k,v]) => params.append(k, v))

// result:
console.log(params.toString())

  • Related