0

I'd like to add the Object to the array of object.

My array is in jsfiddle: https://jsfiddle.net/5w4zhw92/

The Expected

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

2 Answers 2

1

It's already working you just need to declare the variable before using it.Declare sensorType first then use it.

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);
Sign up to request clarification or add additional context in comments.

Comments

1

Just change order of statements in your code. Declare sensorType object first.

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: '' } }];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.