Skip to content
Advertisement

assigning value from object without specifying the index

Let us say I have an object below and I have 2 variable. The length of the object is always fixed.

I wanted to assign the object index attribute value to variable A and object index 1 to variable B.

I can do like A = data[0].attributeValue; and B = data[1].attributeValue;

but is there a better and clean way to do this ? Thanks for any help or any idea. Appreciated.

#sample output

A = 'Test A'
B = 'Test B'

#sample variable

let A = '';
let B = '';

#sample object

 data =  [
        {
            "id": 13,
            "type": "1",
            "attributeValue": "Test A"
        },
        {
            "id": 14,
            "type": "2",
            "attributeValue": "Test B"
        }
    ]

Advertisement

Answer

You can read about Destructuring assignment but it won’t help much .. well maybe a little:

data = [{
    "id": 13,
    "type": "1",
    "attributeValue": "Test A"
  },
  {
    "id": 14,
    "type": "2",
    "attributeValue": "Test B"
  }
]

var [{attributeValue: A}, {attributeValue: B}] = data;
console.log(A, B)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement