Home > Net >  Creating an new object from an existing object in javascript
Creating an new object from an existing object in javascript

Time:07-06

I am going through a challenge from devchallenges.io, Shoppingify challenge. Having read the prompt, I proceeded to create a model which has the following format when a request is made.

{
  "user": 1,
  "_id": 3393220221,
  "name": Chicken,
  "category": "Meat",
  "note": "This is an example note",
  "image_url": "www.exampleurl.com"
}

The issue I'm having is that the component expects the object in the following format.

{
"category": "Meat",
"items": [
{
"user": 1,
"_id": "3393220221",
"name": "Chicken",
"note": "This is an example note",
"image_url": "www.exampleurl.com"
}
]
}

The link to the challenge is https://devchallenges.io/challenges/mGd5VpbO4JnzU6I9l96x for visual reference.

I'm struggling with how to modify the object response from the request. I want to be able to find occurances of the same category name and push the items onto a new object as shown.

CodePudding user response:

const users = [
    {
        "user": 1,
        "_id": 3393220221,
        "name": "Chicken",
        "category": "Meat",
        "note": "This is an example note",
        "image_url": "www.exampleurl.com"
    }
];

function modifyUserObject(users) {
    const result = {};

    users.forEach(user => {
        if (!result[user]) {
            result[user] = {
                category: user.category,
                items: []
            }
        }

        //code here..if want to remove user properties like user

        result[user].items.push(user);
    });

    return Object.values(result);
}

modifyUserObject(users);

Hope this will be helpful! Happy coding...

CodePudding user response:

The value Chicken is not defined. Is this a typing error by you? Anyway this should do the trick:

const obj = {
    user: 1,
    _id: 3393220221,
    name: "Chicken",
    category: "Meat",
    note: "This is an example note",
    image_url: "www.exampleurl.com",
};

function createObj(arg) {
    let result = {
        category: arg.category,
        items: [
            {
                user: arg.user,
                _id: arg._id,
                name: arg.name,
                note: arg.note,
                image_url: arg.image_url,
            },
        ],
    };
    return result;
}

console.log(createObj(obj));
  • Related