简体   繁体   English

如何在JavaScript中将对象添加到对象数组

[英]How to add Object to the array of object in javascript

I'd like to add the Object to the array of object. 我想将对象添加到对象数组。

My array is in jsfiddle: https://jsfiddle.net/5w4zhw92/ 我的数组在jsfiddle中: https ://jsfiddle.net/5w4zhw92/

The Expected 预期的

var sensors = [
{ id: 'led', name: 'LED', type: { port: '', path: '' } },
{ id: 'temp', name: 'TEMP', type: { path: '' } },
];

It's already working you just need to declare the variable before using it.Declare sensorType first then use it. 它已经在工作,您只需要在使用变量之前声明该变量即可。先声明sensorType然后再使用它。

var sensorType = {
    sender: {
        port: '',
        path: ''
    },
    receiver: {
        path: ''
    }
    };
var sensors = [
    { id: 'led', name: 'LED', type: sensorType.sender },
    { id: 'temp', name: 'TEMP', type: sensorType.receiver }
    ];

    console.log(sensorType.sender);
    console.log(sensors);

Just change order of statements in your code. 只需更改代码中语句的顺序即可。 Declare sensorType object first. 首先声明sensorType对象。

 var sensorType = { sender: { port: '', path: '' }, receiver: { path: '' } }; var sensors = [ { id: 'led', name: 'LED', type: sensorType.sender }, { id: 'temp', name: 'TEMP', type: sensorType.receiver }, ]; console.log(sensorType.sender); //Returns Object {port: "", path: ""} console.log(sensors); //[{ id: 'led', name: 'LED', type: { port: '', path: '' } },{ id: 'temp', name: 'TEMP', type: { path: '' } }]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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