1

Say I have an object:

var obj = { a:{}, b:1, c: new Set() };

Objects are not iterable without work and Object.keys/values/entries are not quite what I want. Object.entries() is close, but I would prefer it returns an array of objects instead of a 2D array, ideally with references intact (where appropriate).

So something like:

Object.items( obj ) = [ { a: {} }, { b: 1 }, { c: new Set() } ];

I understand I could create a function to do this using Object.entries(), I just want to confirm that there isn't already something similar.

5
  • 2
    One-property objects make not much sense and are hard to deal with. What do you need this weird format for? No, there is indeed nothing in the standard lib that does this. Commented Mar 1, 2018 at 16:46
  • What do you mean by "with references intact"? Commented Mar 1, 2018 at 16:46
  • 1
    @Bergi Presumably he means that the {} value of a should be the same object in the result. Which is hard to avoid unless you go to extra lengths to make a copy. Commented Mar 1, 2018 at 16:48
  • But if he thinks that changing the value 1 of b in the original will propagate to the result (or vice versa) that can't be done. Commented Mar 1, 2018 at 16:49
  • @Barmar Well {get [key]() { return orig[key]; }, set [key](v) { orig[key] = v; }} could do even that :-) Commented Mar 1, 2018 at 16:50

2 Answers 2

5

You are correct, there is nothing built it that does this. You would need to build your own function and entries is a good starting point.

var obj = { a:{}, b:1, c: new Set() };
var obj2 = Object.entries(obj).map((array) => ({ [array[0]]: array[1] }));

console.log(obj2);
console.log(obj2[2].c === obj.c);

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

1 Comment

You can also use destructuring to get rid of [0] and [1].
0

You could define Symbol.iterator for the object and take single objects with just one property.

var obj = { a:{}, b:1, c: new Set() },
    array;
    
obj[Symbol.iterator] = function* () {
    for (var [key, value] of Object.entries(this)) {
        yield { [key]: value };
    }
};

array = Array.from(obj);

console.log(array);
console.log(array[2].c === obj.c);

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.