1

Given the following object:

const object = {
    greeting: "hi",
    farewell:"bye",
    specialArray:[10,20,30,40,50]
} 

I need to retrieve the 3 first elements of the array into 3 separate variables a , b , c

how?

1
  • 1
    var [a,b,c] = object.specialArray Commented Aug 23, 2017 at 7:14

4 Answers 4

1

Just assign to an array with the variables for a destructuring assignment.

const object = {
        greeting: "hi",
        farewell: "bye",
        specialArray: [10, 20, 30, 40, 50]
    },
    [a, b, c] = object.specialArray;

console.log(a, b, c);

Sign up to request clarification or add additional context in comments.

Comments

0

You can assign it to variables like given in the example

const object = {
    greeting: "hi",
    farewell:"bye",
    specialArray:[10,20,30,40,50]
} 

let [a, b, c] = object.specialArray;

console.log(a, b, c);

Comments

0

I'm not sure that is the answer you expect but what you are asking seems quite simple :

const object = {
    greeting: "hi",
    farewell:"bye",
    specialArray:[10,20,30,40,50]
} 
var [a, b, c] = object.specialArray;
    
console.log('a : ' + a +', b : ' + b + ', c : '+ c)

Comments

0
const object = {
greeting: "hi",
farewell:"bye",
specialArray:[10,20,30,40,50]
};
let [a,b,c, ...rest] = object.specialArray; 
console.log(a); // 10
console.log(...rest); // 40 50

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.