3

In JavaScript, how do you dereference an object returned by a function?

For example this:

var tmp = getTextProperties();
font   = tmp.font;
size   = tmp.size;
color  = tmp.color;
bold   = tmp.bold;
italic = tmp.italic;

PHP has the list() construct which does something similar:

list($font, $size, $color, $bold, $italic) = getTextProperties();
markmoxx
  • 1,492
  • 1
  • 11
  • 21
Richard
  • 4,809
  • 3
  • 27
  • 46

3 Answers3

7

With ES6, you can destructure an object as follows:

var { font, size, color, bold, italic } = getTextProperties();

See JavaScript Destructuring assignment

markmoxx
  • 1,492
  • 1
  • 11
  • 21
  • you should add this answer to the linked it - I don't believe it's mentioned there and this one's likely to get closed – But those new buttons though.. Dec 05 '18 at 17:26
  • @billynoah Thanks, just added it. – markmoxx Dec 05 '18 at 17:29
  • @billynoah I removed it, as I realised it's not asking the same question. In PHP's list() function, you specify the variable names you want to assign the values to. In JS's destructuring, you have to specify the variable names which **already exist** in the object you're destructuring. – markmoxx Dec 05 '18 at 17:54
  • @billynoah ...which is the definitive difference between dereferencing, and destructuring. – markmoxx Dec 05 '18 at 17:55
  • I see your point but not sure it's critical to either question. Since this one explicitly mentions "dereference" and asks for something similar to `list()` it seems like a dupe to me. – But those new buttons though.. Dec 05 '18 at 18:08
  • @markmoxx as of now (in the future!), we have new ways of destrcuturing. We can now rename and assign defaults in destructuring statements. Ponder this: `let obj = {a,: 5, b: 6, c: [7,8],d: {e: 9, f: 10}};` – Werlious Aug 13 '20 at 20:50
1

Destructuring and derefrencing are totally different derefrence the data using Destructuring which is totally wrong play around this..

const data = [
  {
    id: 1,
    name: "Tshirtr",
    img: "add-url",
    price: 714,
    cat: "Dress"
  },
  {
    id: 11,
    name: "short",
    img: "https://m.media-amazon.com/images/I/71e04Q53xlL._AC_UY879_.jpg",
    price: 474,
    cat: "Dress"
  },
  {
    id: 2,
    name: "Timex Men's Expedition Scout ",
    img: "https://m.media-amazon.com/images/I/91WvnZ1g40L._AC_UY879_.jpg",
    price: 470,
    cat: "Sport"
  },
  {
    id: 3,
    name: "Breitling Superocean Heritage",
    img: "https://m.media-amazon.com/images/I/61hGDiWBU8L._AC_UY879_.jpg",
    price: 200,
    cat: "Luxury"
  },
  {
    id: 4,
    name: "Casio Classic Resin Strap ",
    img: "https://m.media-amazon.com/images/I/51Nk5SEBARL._AC_UY879_.jpg",
    price: 16,
    cat: "Sport"
  },
  {
    id: 5,
    name: "Garmin Venu Smartwatch ",
    img: "https://m.media-amazon.com/images/I/51kyjYuOZhL._AC_SL1000_.jpg",
    price: 74,
    cat: "Casual"
  }
];

console.log("data-46", data);
// lets destructur--
const [one, ...rest] = data;
console.log("one-49", one);

one.boy = { name: "rahul", age: 24 };

console.log("one-53", one);
console.log("data-54", data);
// here you can see data also gets changed
// destructuring doesn't means derefrence

// just used below single line of code to dereferene the data that is cloning
const cloneData = JSON.parse(JSON.stringify(data));
console.log("cloneData", cloneData);
cloneData.push({ 99: "data no more refrencing.." });
console.log("cloneData-62", cloneData);
console.log("data-62", data);
RAHUL RAJ
  • 91
  • 4
0

To add onto what @markmoxx said, as of now (form the future!), we have new ways of destructuring. We can now rename and assign defaults in destructuring statements. Ponder this:

let obj = {a,: 5, b: 6, c: [7,8],d:[9,10]e: {f: 11, g: 12}};

let {a: first, b: second, c: arr, d: [innerFirst, innerSecond], e: {f: objFirst, g: objSecond}, h = "default1", i: [defaultArr1 = "default2", defaultArr2 = "default3"], j: {k: objDefault1 = "default4"} } = obj;

console.log(first, second, arr, innerFirst, innerSecond, objFirst, objSecond, h, defaultArr1,defaultArr2, objDefault1);

// This outputs: 
5, 6, [7,8],9,10,11,12,"default1","default2","default3","default4"

So, now we have more control over destructuring assignments.

Edit: for congruence

PHP's list function is mostly for arrays (mostly). And at that, has some weird behavior (reverse assignment depending on php version, etc). Destructuring in javascript is different. Even with the renaming syntax above, you still need to know the object keys/array indices. Also (this may be a matter of preference but), destructuring in javascript has more power, in that arrays and objects can both be destructured, to any nested depth, while allowing you to rename and assign defaults. But be warned, because destructuring can easy get out of hand. Consider this example of over-zelous destructuring:


const NameView = ({context: { state: [ state, update ], id, display: {tag, size = 32, type = "text", style: { wrapper: outerouter = "card", content: innerouter = "content", banner: {wrapper: outerinner = "title",content: innerinner = "content"} } } } }) => (
    <div className={outerouter}>
        <input className={innerouter} type={type} maxlength={size} size={size} value={name} id={id} name={id} onChange={(e) => update(e.target.value)}/>
        <div className={outerinner}>
            <label for={id} className={innerinner}>{tag}</label>
        </div>
    </div>
)

Werlious
  • 583
  • 6
  • 15