如何从javascript中的对象数组中检索数组值和字符串

时间:2017-12-02 11:31:00

标签: javascript

var details = [
        {
            name: "Shiva",
            designation: "SE",
            address: {
                streetno: '15',
                mobileno: [987894451, 7852141222],
                area: 'gachibowli',
                city: 'Hyd'
            }
        },
        {
            name: "Rajesh",
            designation: "SE",
            address: {
                streetno: '13',
                mobileno: [885211111, 85221102],
                area: 'Tolichowki',
                city: 'Hyd'
            }
        },
        {
            name: "Prasad",
            designation: "SE",
            address: {
                streetno: '10',
                mobileno: [885211111, 85221102],
                area: 'KPHB',
                city: 'Hyd'
            }
        }
        ];

1 个答案:

答案 0 :(得分:0)

details[0]将返回数组中的第一个对象

  

{name:“Shiva”,名称:“SE”,地址:{...}}

details[0]['name']将返回第一个对象的属性名称

  

“希瓦”

这应该给你一个很好的起点:

var str = ''; 
details.forEach(person => {
     var address = person.address;   
     var mobiles = address.mobileno;
     str += `Name ${person.name}\nDesignation: ${person.designation}\nPhone: ${mobiles.join(' ')}\nStreet No: ${address.streetno}\n\n`; 
})

console.log(str)

让代码尽可能可读是非常重要的,所以尽量保持整洁:)

总是想到下一个会出现并编写代码的程序员。