Home > other >  How to insert object inside an object in javascript?
How to insert object inside an object in javascript?

Time:10-29

I'm trying to insert an object inside another object and with what I tried I wasn't successful in any of the, let's say I want to insert an object inside an object, these are the ways I tried:

var ob = {
 user1: {name: 'chris'}
};

1:
ob['user2']['name'] = 'Luana'; //error

2:
var obA = ob['user2'];
obA['name'] = 'Luana'; //error

3:
ob['user2'] = ['name'] = 'Luana'; //error
 

These are the ways I tried, but since I am not successful, how can I insert other properties, other than this way below?

obA['user2'] = {name: 'Luana'}; // for me this is not what i'm looking for

CodePudding user response:

the key I'm trying to enter is a variable eg: var key = 'user'; var keyI = 'name'; ob[key][keyI] = 'name'

Perhaps you meant this?

var obj = {
  user1: {
    name: 'chris'
  }
};
console.log(obj)

let key = 'somekey'
let key1 = 'someotherkey'
let val = 'somevalue'
obj[key] = {[key1] : val}

console.log(obj)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

javascript add to object

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

// Array of Objects in form {element: {id: 10, quantity: 10} }
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

example :

// Original object
var lunch = {
  sandwich: 'turkey',
  drink: 'soda',
  chips: true
};

// Add to the end of the object
var lunchWithDessert = addToObject(lunch, 'dessert', 'cookie');

// Add between sandwich and drink
var lunchWithTopping = addToObject(lunch, 'topping', 'tomato', 1);

// Immutable copy of lunch
var lunchClone = addToObject(lunch);

Working!!!!

var obj = { Name: "Joe" };

obj.Age = 12;
console.log(obj.Age)

obj['Country'] =  "USA"
console.log(obj.Country)

Ref : javascript tutorial

CodePudding user response:

There is another regularly way.

You could try this:

var ob = {
 user1: {name: 'chris'}
};

var ob2 =  {
 user2: {name: 'Luana'}
};
var result = Object.assign(ob, ob2);
console.log(result); 
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This is the way is should be done

var ob = {
 user1: {name: 'chris'}
};

ob.user2 = {name: 'Luana'}; // option 1
ob['user3'] = {name: 'Luana3'}; // option 2



console.log(ob);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Not possible in that way.

var ob = {
 user1: {name: 'chris'}
};

//If you wanna do this, it will show you an error since 'user2' does not exists on ob:
ob['user2']['name'] = 'Luana'

// So yo wanna create it first:
ob['user2'] = {name: 'chris'};
  • Related