0

For example, given this object:

let foo = {foo:1};
let bar = {a:foo,b:foo};

We can define bar as a single expression by writing it as:

let bar = (($0)=>({a:$0={foo:1},b:$0}))()

However, given this object:

let o = {a:'perfect'};
o.circle = o;

Is it possible to recreate the structure of o with a single expression?


This won't work:

(($0)=>($0={a:"perfect",circle:$0}))()

Because circle is nested and $0 has been defined yet.

5
  • Would using Object.assign() be able to do what you want? I feel like it might. Commented Aug 18, 2017 at 2:32
  • ({...$0={a:'perfect'},circle:$0}). Use Object.assign as necessary. I really don't see why you need this. Commented Aug 18, 2017 at 2:33
  • @AndrewLi That won't create a reference cycle but just lead to the same result as {a:'perfect',circle:{a:'perfect'}} Commented Aug 18, 2017 at 3:06
  • @Bergi Oh, I see. They want circle also in the circle property? Commented Aug 18, 2017 at 3:07
  • @AndrewLi Yes, I think so. Object.assign($0={a:'perfect'}, {circle:$0}) could do that. Commented Aug 18, 2017 at 3:14

1 Answer 1

1

Unless you want to solve this with getter properties, an assignment is unavoidable.

There are all kinds of ways to do that, even within a single expression:

let o = (o = {a:'perfect'}).circle = o;

But I would recommend to focus on clarity and use an IIFE instead:

const o = (function(){
    const x = {a:'perfect'};
    x.circle = x;
    return x;
}());
// more like the first solution but without the mutable `o` variable:
const o = (x => x.circle = x)({a:'perfect'});
Sign up to request clarification or add additional context in comments.

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.