Reputation: 1051
I am new to NodeJS - I am doing this in a AWS lambda function and have the below JSON object
{
"subnetsToUse": [
{
"subnetId": "subnet-0g6e5ad78f2841dc9" },
{
"subnetId": "subnet-089e0d4de075664b3" },
{
"subnetId": "subnet-06778539a55adc513" }
]
}
I need to return a list of subnetIds from this.
subnet-0g6e5ad78f2841dc9,subnet-0g6e5ad78f2841dc9,subnet-0g6e5ad78f2841dc9
Here is what I have tried so far
var objectKeysArray = Object.keys(subnetsToUse)
objectKeysArray.forEach(function(subnetId)
{ var objValue = subnetsToUse[subnetId] })
How do I achieve this in NodeJS.
Upvotes: 0
Views: 898
Reputation: 2531
You can use the Array.map
or Array.reduce
to iterate over the object values and push them into an array for example.
const data = {
"subnetsToUse": [
{
"subnetId": "subnet-0g6e5ad78f2841dc9",
"availabilityZone": "us-west-2c"
},
{
"subnetId": "subnet-089e0d4de075664b3",
"availabilityZone": "us-west-2b"
},
{
"subnetId": "subnet-06778539a55adc513",
"availabilityZone": "us-west-2a"
}
]
}
const mapRes = data.subnetsToUse.map((currentValue) => {
return currentValue.subnetId;
});
console.log("mapRes", mapRes)
const reduceRes = data.subnetsToUse.reduce((accumulator, currentValue) => {
accumulator.push(currentValue.subnetId);
return accumulator;
}, []);
console.log("reduceRes",reduceRes)
Upvotes: 1