The question might seem silly and unclear because I essentially don't know what approach I should take in order to achieve this, but it will make more sense when I give examples.
So, lets say we have the following array:
const arr = [{key1: 'value1', key2: 'value2'}, {key1: '', key2: 'value2'}, {key1: 'value1', key2: 'value2'}]
As you can see, the item at index 1 has no value for the 'key1'
key , but I can get this value from an http request.
What I'm ultimately trying to achieve is loop through the array, check if key1
has a value, if not make an http request to get said value and get a new array where all the indexes have a value for key1
.
Something like this ( which obviously doesnt work )
const arr = [{key1: 'value1', key2: 'value2'}, {key1: '', key2: 'value2'}, {key1: 'value1', key2: 'value2'}];
arr.map(i => {
if (!i.key1) {
const value = getValueFromHttpRequest();
return {
...i,
key1: value
}
}
return i;
})
So a working example of an array I would get would be
[{key1: 'value1', key2: 'value2'}, {key1: 'valueFromHttpRequest', key2: 'value2'}, {key1: 'value1', key2: 'value2'}]
I know it sounds confusing, but I appreciate any help I can get with this.
CodePudding user response:
If you're inside an async function already, you can request them 1 at a time using a standard for loop
for (const el of arr) {
if (el.key1) continue; // skip all elements that already have key1
const response = await requestInfo();
el.key1 = response.something; // this is what I mean by 'edit the array as you go'
...
}
CodePudding user response:
You can use Promise.all
to get an array of responses.
const arr = [{key1: 'value1', key2: 'value2'}, {key1: '', key2: 'value2'}, {key1: 'value1', key2: 'value2'}];
const result = Promise.all(arr.map(async (i) => {
const value = await sendRequest();
return value;
}));
CodePudding user response:
You can loop over the keys and for empty key1
s you can make an API call and get the value.
const getKey1 = () =>
new Promise((res) => setTimeout(() => res("value1")), 1000);
const keys = [
{ key1: "value1", key2: "value2" },
{ key1: "", key2: "value2" },
{ key1: "value1", key2: "value2" },
];
async function fillMissingKeys(keys) {
return Promise.all(
keys.map(async ({ key1, key2 }) => ({
key1: !key1 ? await getKey1() : key2,
key2,
}))
);
}
fillMissingKeys(keys).then(console.log);
CodePudding user response:
Short regular expression string of text regex allows you create patterns that helps matches, locate and manage texton http request,fully specified a RESt API depending request web server content cache,regex called rational expression sequence characters that define a search pattern, mainly for use...