0
var obj={"firstName":"John","lastName":"Smith","isAlive":true,"age":25,"address":{"streetAddress":"21 2nd Street","city":"New York","state":"NY","postalCode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"},{"type":"mobile","number":"123 456-7890"}],"children":[],"spouse":null};

I want to access the phoneNumbers field So I use

phone=obj.phoneNumbers;

I get an array but without "phoneNumbers" field.I want to get someting like this:

{
 "phoneNumbers": [
 {
 "type": "home",
 "number": "212 555-1234"
 },
 {
 "type": "office",
 "number": "646 555-4567"
 },
 {
 "type": "mobile",
 "number": "123 456-7890"
 }
 ]
}
asked May 31, 2017 at 16:51
3
  • and why should this be useful? Commented May 31, 2017 at 16:56
  • because my API ask for it Commented May 31, 2017 at 16:59
  • @Yakov You can check my answer. Commented May 31, 2017 at 17:01

3 Answers 3

3

You have to create a new object then

var phone = { "phoneNumbers": obj.phoneNumbers };
answered May 31, 2017 at 16:54
Sign up to request clarification or add additional context in comments.

Comments

3

You can add that part in:

var phone = {"phoneNumbers" : obj.phoneNumbers};

Although there should be a good reason for doing this (like, need to pass it to an API that expects exactly "x"). A single-property object is about as useful as the value of its single property.

answered May 31, 2017 at 16:53

Comments

1

How about making a function and using it for other similar purposes:

function transform (prop, payload) {
 return { [prop]: payload };
}

And use it like:

phone = transform('phoneNumbers', obj.phoneNumbers);
answered May 31, 2017 at 16:57

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.