将多个对象作为值添加到另一个对象中的键

时间:2016-08-04 17:40:30

标签: javascript arrays object

对标题感到抱歉 - 我不知道如何解释它。但是,我正在初始化一个这样的对象:

var form = {};
form.title = 'Titel';
form.fields = { type: 'radio', label: 'First name', id: 1 }

然后我添加到对象:

form.fields.choices = { text : "Standard", value : "Standard" , isSelected : false, price : ''};

这给了我以下数组:

Array (
    [title] => Titel
    [fields] => Array
        (
            [type] => radio
            [label] => First name
            [id] => 1
            [choices] => Array
                (
                    [text] => Standard
                    [value] => Standard
                    [isSelected] => false
                    [price] => 
                )

        )

)

但是,我想在选择键中添加多个数组,如下所示:

Array (
    [title] => Titel
    [fields] => Array
        (
            [type] => radio
            [label] => First name
            [id] => 1
            [choices] => Array(
                Array (
                    [text] => Standard1
                    [value] => Standard1
                    [isSelected] => false
                    [price] => ),
                Array (
                    [text] => Standard2
                    [value] => Standard2
                    [isSelected] => false
                    [price] => )

                )
            )

)

我将如何实现这一目标?

3 个答案:

答案 0 :(得分:2)

将选项设为数组

form.fields.choices = []

然后

form.fields.choices[0] = { text : "Standard", value : "Standard" , isSelected : false, price : ''}

form.fields.choices[1] = { text : " Standard 2", value : "Standard" , isSelected : false, price : ''}

答案 1 :(得分:0)

这样的东西?相应地添加增量值和另一个数组。

    var choices = [];

    const choice = {
       <values>
    };

    Object.keys(choice).forEach((key, index) => {
        if (data.search(key) !== -1) {
            choices.push(choice[key]);
        }
    });

答案 2 :(得分:0)

var form = [];

var form_object = {};
form_object.title = "Title";
form_object.fields = [];

var field_object = {};
field_object.type = "Radio";
field_object.label = "First name";
field_object.id = 1;
field_object.choices = [];

var choice_object1 = {};
choice_object1.text = "Standard";
choice_object1.value = "Standard";
choice_object1.isSelected = false;
choice_object1.price = '';

var choice_object2 = {};
choice_object2.text = "Standard 2";
choice_object2.value = "Standard 2";
choice_object2.isSelected = false;
choice_object2.price = '';

field_object.choices.push(choice_object1);
field_object.choices.push(choice_object2);

form_object.fields.push(field_object);

form.push(form_object);