简体   繁体   中英

How to parse complex nested JSON data in NodeJS

I'm having kind of complex nested JSON in my dynamoDB, I want to extract this Filter object and its values. For example, if Type is macBook return the Filter object and its value PRO and AIR . Please find my code below and JSON input - I'm struggling to parse these value in NodeJS - could someone please help me - how to get the Filter Object?

JSON

{
  "ProductType": {
    "S": "Apple"
  },
  "Type": {
    "M": {
      "iPhone": {
        "M": {
          "Filter": {
            "M": {
              "model": {
                "SS": [
                  "X", "XS"
                ]
              }
            }
          }
        }
      },
      "macBook": {
        "M": {
          "Filter": {
            "M": {
              "model": {
                "SS": [
                  "PRO", "AIR"
                ]
              }
            }
          }
        }
      }
    }
  }
}

product.js

const AWS = require('aws-sdk');

var dynamodb = new AWS.DynamoDB({
    region: process.env.AWS_REGION,
  });

const getModel = function (productType) {
    return new Promise((resolve, reject) => {
        var params = {
            Key: {
                "ProductType": {
                    S: productType
                }
            },
            TableName: 'product'
        };
        dynamodb.getItem(params, function (err, data) {
            if (err) reject(err, err.stack);
            else {
                console.log("data: " + Object.keys(data));
                let product = data.Item.ProductType.S;
                let filterModel = data.Item.Type.M
                console.log(filterModel);

                
                
            }

        });
    });
}

getModel('Apple')

Any help would be much appreciated

You need to use Object.values to get the values of iPhone and macbook objects, then inside you can use flatMap to find the Filter whose has PRO", "AIR" properties.

 const data ={ "ProductType": { "S": "Apple" }, "Type": { "M": { "iPhone": { "M": { "Filter": { "M": { "model": { "SS": [ "X", "XS" ] } } } } }, "macBook": { "M": { "Filter": { "M": { "model": { "SS": [ "PRO", "AIR" ] } } } } } } } } const result = Object.values(data.Type.M).flatMap((item) => { const SS = item.M.Filter.M.model.SS return SS.includes('PRO') && SS.includes('AIR') ? [{ Filter: item.M.Filter.M }] : [] }, []) console.log(result)

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