-1

I am trying to create customized product order in this I need to store all selected options store in the JSON.

like this

let attr = [{
        fabric: 'Bargandi Check',
        style:[{
                 Jacket lapels: 'Notch'
        }],
    }];

selector image for understanding batter

I want when user select any of these options I will store in JSON when a user updates any of option it will update in the JSON object and when user select the new option it will add in JSON

like this

let attr = [{
        fabric: 'Bargandi Check',
        style:[{
                 Jacket lapels: 'Notch',
                 Lapel width: 'Slim' // this
        }],
    }];
2

1 Answer 1

0

You cannot "push" an element into a Javascript object. but you can either use the dot operator or square brackets to access an existing property / rewrite property / assign property

const obj = { name: 'ed', age: '16' };

// rewriting an existing property
obj["age"] = 20; 
obj["name"] = 'edward'; 

console.log(obj["skill"]); // will be undefined
obj["skill"] = "Javascript"; // setting it as a new property

obj["list"] = []; // the list property is an array

obj["list"].push(1); // now i can use push because its an array
console.log(obj);

One more thing, javascript properties cannot have blank spaces, but you can seperate it with a hyphen or an underscore

"An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation" - MDN

Your Corrected Object

let attr = [{
    fabric: 'Bargandi Check',
    style: [{
        Jacket_lapels: 'Notch',
        Lapel_width: 'Slim' // this
    }],
}];


const found = attr.find(x => x.fabric == 'Bargandi Check');
found.style[0].Lapel_width = 'Thick' // this will rewrite the width property to "thick"

console.log(attr);

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

2 Comments

I am very thankful to you for my helping. but I don't need it find(x => x.fabric == 'Bargandi Check');
ah okay, glad to help :) please consider marking the answer as a correct one if it helped you

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.