0

Do you know guys how to do it simplier/smarter ?

I wanna add a label key with name value if the key doesn't exist in object. This is my list:

myList = [
    {
        name: 'Candy',
        label: 'xx',
    },
    {
        name: 'Mike',
        label: 'yy',
    },
    {
        name: 'Betty',
    }
]

And my solution:

assignLabel = list => {
        const casesWithoutLabel = list.filter(({ label }) => !label).map(item => ({
            ...item,
            label: item.name
        }))

        const casesWithLabel = list.filter(({ label }) => label)

        return [ ...casesWithoutLabel, ...casesWithLabel ]
}

assignLabel(myList)

Output

[
    {
        name: 'Candy',
        label: 'xx',
    },
    {
        name: 'Mike',
        label: 'yy',
    },
    {
        name: 'Betty',
        label: 'Betty'
    }
]

It gives me good output, but it's not elegant and I don't have idea how to improve now. Please help me!

2 Answers 2

2

I have create simple script for you, please have a look!

let myList = [
    {
        name: 'Candy',
        label: 'xx',
    },
    {
        name: 'Mike',
        label: 'yy',
    },
    {
        name: 'Betty',
    }
];

let list = myList.map((item) => {
  let {name, label} = item;
  if(label == undefined){
    item["label"] = name;
  }
  return item;
});

console.log(list);

Sign up to request clarification or add additional context in comments.

1 Comment

Your Welcome! Happy to hear!
0

Your code seems very advanced for only assigning a property, so maybe I am missing something, but you could simply loop through the list (or filter oc)

myList = [{name: 'Candy',label: 'xx',},{name: 'Mike',label: 'yy',},{name: 'Betty',}];

for(const obj of myList)
    if(!obj.label)obj.label = obj.name;
 
console.log(myList);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.