0

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?

2
  • 1
    push is array method - so don't have an array and don't push - also why not just create the object as desired in one go? Commented Sep 8, 2017 at 14:14
  • 1
    where is the problem? an array does not work if you need a plain object. it looks more like a problem (how) to write object literals. Commented Sep 8, 2017 at 14:20

1 Answer 1

2

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);

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.