Marin Leontenko
Marin Leontenko

Reputation: 771

Append JavaScript object property with another object

I have the following JavaScript code:

var title = 'Some title';
var date = [];
var dateKey = 'revision';
var dateValue = '2010-09-20';
var obj = {};
obj['dateKey'] = dateKey;
obj['dateValue'] = dateValue;
date.push(obj);
var inObj = {
  "title": title,
  "date": date
};
console.log(inObj);

When i output inObj in console i get:

{"title":"Some title","date":[{"dateKey":"revision","dateValue":"2010-09-20"}]}

But, i dont want "date" property value to be an array. I need the output to look like this (without square brackets []):

{"title":"Some title","date":{"dateKey":"revision","dateValue":"2010-09-20"}}

I understand that date variable is an array, but i need it to be an object that appends another object's property (because there will be multiple dates so i need to lop through them and add them to "date" property of inObj). If i remove the second line of code (var date = [];), the code won't run. How can i solve this?

Upvotes: 0

Views: 76

Answers (1)

Ori Drori
Ori Drori

Reputation: 192732

Skip the date array, and set the obj as the date property:

var inObj = {
  "title": title,
  "date": obj
};

Example:

var obj = {
  dateKey: 'revision',
  dateValue: '2010-09-20'
};

var inObj = {
  "title": 'Some title',
  "date": obj
};

console.log(inObj);

Upvotes: 2

Related Questions