如何在jQuery中向对象数组添加数组对象元素:定制化产品订单选中选项的JSON存储与更新实现
Hey there! Let's figure out how to smoothly manage your custom product order attributes in JSON. Based on your example, here's a practical JavaScript solution that handles adding new options, updating existing ones, and keeps your structure consistent exactly as you need.
Your initial attr structure is an array holding a single product object. We'll target that first object (attr[0]) for all operations. The style array inside it contains one object where we'll store all style-related selections—this makes it easy to add or update style properties without restructuring the entire array.
First, let's start with your initial structure:
let attr = [{ fabric: 'Bargandi Check', style: [{ 'Jacket lapels': 'Notch' }], }];
1. Update or Set Fabric
This simple function handles updating the fabric selection, with a safety check to ensure the product object exists even if attr starts empty:
function updateFabric(newFabric) { // Create a default product object if attr is empty if (!attr[0]) { attr.push({ fabric: '', style: [{}] }); } attr[0].fabric = newFabric; }
Usage example:
updateFabric('Cotton Twill'); // Updates fabric to 'Cotton Twill'
2. Add or Update Style Options
This function handles both adding new style properties and updating existing ones. It ensures the style object exists before making changes:
function updateStyleOption(optionKey, optionValue) { // Ensure product and style objects exist if (!attr[0]) { attr.push({ fabric: '', style: [{}] }); } if (!attr[0].style[0]) { attr[0].style.push({}); } // Either update existing key or add a new one attr[0].style[0][optionKey] = optionValue; }
Usage examples:
// Add a new style option updateStyleOption('Lapel width', 'Slim'); // Update an existing style option updateStyleOption('Jacket lapels', 'Peak');
3. Combined Function (Optional)
If you want a single function to handle both fabric and style updates, use this:
function updateAttribute(type, key, value) { // Ensure base product structure exists if (!attr[0]) { attr.push({ fabric: '', style: [{}] }); } if (type === 'fabric') { attr[0].fabric = value; } else if (type === 'style') { attr[0].style[0][key] = value; } }
Usage examples:
updateAttribute('fabric', '', 'Wool Blend'); updateAttribute('style', 'Pocket type', 'Flap');
After running the style updates, your attr will look like this:
console.log(attr); // Output: // [{ // fabric: 'Bargandi Check', // style: [{ 'Jacket lapels': 'Peak', 'Lapel width': 'Slim' }], // }]
- If you ever need to support multiple products (multiple objects in
attr), just adjust the functions to accept a product index as an argument. - The safety checks prevent runtime errors if
attrstarts empty or if the style object is missing.
内容的提问来源于stack exchange,提问作者Muhammed saad

