在Javascript中从对象中检索数组对象

时间:2017-05-31 16:51:38

标签: javascript

12345

我想访问phoneNumbers字段 所以我用

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

我得到一个数组,但没有" phoneNumbers" field.I想得到这样的东西:

phone=obj.phoneNumbers;

3 个答案:

答案 0 :(得分:3)

您可以添加该部分:

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

虽然应该有充分的理由这样做(例如,需要将其传递给期望完全“x”的API)。单个属性对象与其单个属性的值一样有用。

答案 1 :(得分:3)

你必须创建一个新对象

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

答案 2 :(得分:0)

如何制作一个功能并将其用于其他类似用途:

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

并使用它:

phone = transform('phoneNumbers', obj.phoneNumbers);