[英]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. 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阵列 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. 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
.我想您是在问如何使用单个 object 和
MyIp
属性创建一个新数组,该属性的值是ServiceAddress
和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: map
是这样做的惯用方式,也许需要进行一些解构以从每个 object 中挑选出属性,并使用模板文字来构建结果字符串:
const result = bodyObject.map(({ServiceAddress, ServicePort}) => {
return {MyIp: `http://${ServiceAddress}:${ServicePort}`};
});
or with a concise-form arrow function:或使用简洁的箭头 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.) (您需要
()
在 object 文字周围,否则它看起来像解析器的箭头 function 的完整 function 主体形式。)
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:其中有相当数量的新 JavaScript 功能,所以为了清楚起见,这里有一个没有解构或模板文字的版本:
const result = bodyObject.map(element => {
return {MyIp: "http://" + element.ServiceAddress + ":" + element.ServicePort};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.