简体   繁体   中英

How to create complex javascript objects

I'm trying to create a javascript object to send as a parameter.

I need to send it in this format:

params (Object) (defaults to: {}) —
    Bucket — required — (String)
    Delete — required — (map)
        Objects — required — (Array<map>)
            Key — required — (String) Key name of the object to delete.

How can I construct this object and fill it out?

I'm doing this:

var params = {
    Bucket : data.bucket,
    Delete: [{
    Objects:[{ Key:""}] }]  
};

for(i=0;i<data.keys.length;i++){
    params.Delete[0].Objects.push({Key: data.keys[i]})
}

And I get an error message from the library saying that my object is missing the key Objects inside of Delete

When I console.log params I get

{ Bucket: 'ct.presentations',
Delete: [ { Objects: [Object] } ] }

What's the best way for creating objects like this?


As Alex pointed out below, map in Javascript, isn't a type of array like I thought it was, so instead of

Delete:[{ I should have done Delete:{

You've made Delete an array containing an object that has Objects as a key. Sounds like it shouldn't be an array:

var params = {
        Bucket : data.bucket,
        Delete: {
            Objects: []
        }
    };

    for(i=0;i<data.keys.length;i++){
        params.Delete.Objects.push({Key: data.keys[i]})
    }

Also note that I removed the {Key: ""} from inside the [] in Objects (on the fourth line). If you really meant to have an object with an empty key as the first entry in the array, add that back, but I suspect you didn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM