'How can I get nested objects, which have not empty values?

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 ?



Solution 1:[1]

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));

Solution 2:[2]

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Andy