How to return object?

CharlieC

Javascript

Object

var initialstate = {
  ddd:{
    aa: '',
    aaa: ''
  }

Syntax Error

return {
  ddd.aa = action.aa,
  ddd.aaa = action.aaa
}

No Error

return {
  aa = action.aa,
  aaa = action.aaa
}

How can I return a javascript object with mutiple values which are nested

gdyrrahitis

You are violating JavaScript syntax for objects.

An object literal have the following rules:

  • A colon separates property name from value.
  • A comma separates each name-value pair from the next.
  • There should be no comma after the last name-value pair.

This is an object literal:

var obj = {};

You can assign properties and values to them using the following syntax:

var obj = {
   myStringProperty: "a string value",
   myNumberProperty: 15,
   myBooleanProperty: false,
   myArrayProperty: [...],
   myFunctionProperty: function (...) {...},
   myComplexProperty: {
       name: "My Name",
       surname: "My Surname",
       family: {
           father: {
               name: "His name",
               age: 60
           }
       }
   }
}

As you can see you can have any valid JavaScript primitive type or complex nested objects or arrays or functions as properties. Anything that is valid JavaScript.

For complex names with special characters, for example "my.car" you can have your property in quotation marks, like the following:

var obj = {
   "my.car": {
        brand: "Brand",
        model: "Model"
    }
} 

To fetch the "my.car" object, you don't use the dot notation, but square brackets, just like you would do on a dictionary to fetch the value by the key. Like this:

var item = obj["my.car"]; // returns the object defined previously

Check some simple, 101 tutorials please, like these:

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related