简体   繁体   中英

How to iterate over only specific keys from a JSON array object using javascript

I am having a below json array and now I need to iterate over the json object to retrieve two values of fields ServicePort And ServiceAddress and form a final output as {"MyIp": "http://IP:Port"} from my json array object.

var bodyObject = [
    {
        "ServiceAddress": "10.X.X.125",
        "ServiceConnect": {},
        "ServicePort": 80
    },
    
    {
       
        "ServiceAddress": "10.X.X.126",
        "ServiceConnect": {},
        "ServicePort": 80
    }
];

I have tried as below to iterate

for (var key in bodyObject ) {
       if (bodyObject.hasOwnProperty(key)) {
          console.log(bodyObject[key].ServiceAddress);
          console.log(bodyObject[key].ServicePort);
       }
       }

How can I form a output final output like {"MyIp": "http://IP:Port"} from my json array object each hitting giving me a diffrent Ip's from my above JSON list dynamically. Can someone help on this please

I think you're asking how to create a new array with a single object with a MyIp property whose value is the combination of ServiceAddress and ServicePort . map is the idiomatic way to do that, perhaps with some destructuring to pick out the properties from each object and a template literal to build the resulting string:

const result = bodyObject.map(({ServiceAddress, ServicePort}) => {
    return {MyIp: `http://${ServiceAddress}:${ServicePort}`};
});

or with a concise-form arrow function:

const result = bodyObject.map(({ServiceAddress, ServicePort}) =>
    ({MyIp: `http://${ServiceAddress}:${ServicePort}`})
);

(You need the () around the object literal because otherwise it looks like the full function body form of arrow function to the parser.)

Live Example:

 const bodyObject = [ { "ServiceAddress": "10.XX125", "ServiceConnect": {}, "ServicePort": 80 }, { "ServiceAddress": "10.XX126", "ServiceConnect": {}, "ServicePort": 80 } ]; const result = bodyObject.map(({ServiceAddress, ServicePort}) => ({MyIp: `http://${ServiceAddress}:${ServicePort}`}) ); console.log(result);

That has a fair number of newish JavaScript features in it, so just for clarity here's a version without destructuring or a template literal:

const result = bodyObject.map(element => {
    return {MyIp: "http://" + element.ServiceAddress + ":" + element.ServicePort};
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM