I have write this function
export const func = (object) => {
return Object.fromEntries(Object.entries(object).filter(([, {
url,
value
}]) => {
return (url && url !== '') || (value && value !== '');
}).map(([key, { url, value }]) => {
return [key, url ? url : value];
}));
};
its return Object with key value pair
{
exampleKey: "someNotEmptyUrl"
}
but i want it to return this type of object
{
action: exampleKey
url: "someNotEmptyUrl"
}
maybe i used to be write reduce instead of map ?
CodePudding user response:
You can try using Object.entries
and then spread operator to build a new object:
const func = (object) => {
let [action,v] = Object.entries(object).find(([k,v]) => !!v.url);
return ({ action, ...v });
};
const obj = { "action1": {"url": ""}, "action2": {"url": ""}, "action3": {"url": ""}, "action4": {"url": "notEmpty"}, "action5": {"value": ""} };
console.log(func(obj));
CodePudding user response:
In case you have more than one object with a non-empty URL value create a new array and push
new objects into it.
const obj={action1:{url:""},action2:{url:"notEmpty2"},action3:{url:""},action4:{url:"notEmpty4"}};
const arr = [];
for (const [action, value] of Object.entries(obj)) {
const { url } = value;
if (url) arr.push({ action, url });
}
console.log(arr);