YAKOVM
YAKOVM

Reputation: 10153

Retrive array object from object in Javascript

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"
    }
  ]
}

Upvotes: 0

Views: 57

Answers (3)

Umair Sarfraz
Umair Sarfraz

Reputation: 6104

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

Upvotes: 1

Quartal
Quartal

Reputation: 410

You have to create a new object then

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

Upvotes: 3

James
James

Reputation: 22246

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.

Upvotes: 3

Related Questions