2

I am trying to make an Object with key as a number and value as an array of objects. How can this be done in javascript?

I want to create an object that looks like this:

{Key: "1", value: [Object, Object, ...], key: "2", value: [Object, Object, ...], key:"N", value: [Object, Object, ...]}

How is this possible in javascript/typescript ?

I tried:

let myObj = {};
myObj["1"] = myObj["1"].push(Object)

Above code does not work.

1
  • 1
    1) .push returns a number, I don't think you want to assign a number to myObj["1"] 2) You can't have the same key twice, so your wanted datastructure is impossible to achieve (and senseless), maybe you want an array of objects? Commented Jun 24, 2019 at 22:27

2 Answers 2

2

push returns the new length of the array - so just call the function (doing nothing with the return value), making sure you've initialized the target array first:

let myObj = {};
myObj["1"] = myObj["1"] || [];
myObj["1"].push(Object);

You could also define a custom type:

type objectContainingObjects = { [key: string]: object[] }
Sign up to request clarification or add additional context in comments.

Comments

1

This is possible, and it can be achieved in a number of ways. For instance, to achieve what you require with TypeScript, you could do the following:

/* Define a type describing the structure of your desired object (optional)
 */    
type CustomType = { [key: number]: Array<any> };

/* Create your object based on type definition with numbers as keys and array
   of objects as values */
const yourObject: CustomType = {
  1 : [1,2,3],
  2 : ['a','b','c'],
  3 : [ new Object(), new Object() ]
};

In JavaScript, the same can be achieved by omitting the typing:

const yourObject = {
  1: [1, 2, 3],
  2: ['a', 'b', 'c'],
  3: [new Object(), new Object()]
};

console.log(yourObject);

/* Adding more letters to value at key 2 */
yourObject[2].push('d', 'e', 'f');

console.log(yourObject);

Hope that helps!

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.