0

I have one JSON Object and I want to create subset of JSON with particular keys values.

JSON Object

{
    "Checksum": "OK",
    "ID": "012B4567",
    "DOB: "12-12-1991"
    "Data": "Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>",
    "issue: "11-April-2015",
    "DocID": "PASSPORT",
    "Number: "123456789",
    "Document": "PASSPORT",
    "Photo": "Qk06AAAAAAAAA",
    "ExpiredFlag": false,
    "ExpiryDate": "01 Apr 12",
    "Forename": "IMA Phoney",
    "Image2": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
    "ImageSource1": 0,
    "Image3": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
    "Image1": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
    "IssueState: "USA",
    "Nationality": "USA",
    "PlaceOfBirth": "U.S.A",
    "SecondName": "J",
    "Sex": "Male",
    "Surname": "XYZ"
}

I want subset from above like below:

{
"ID": "012B4567",
"Number: "123456789",
"Document": "PASSPORT",
 "IssueState: "USA",
 "Nationality": "USA",
 "PlaceOfBirth": "U.S.A",
 "SecondName": "J",
 "Sex": "Male",
 "Surname": "XYZ"
}

I have tried below code. It is working fine, But I am not able to understand. I need simplest way:

    var data={
        "CDRValidation": "CDR Validation test passed",
        "AirBaudRate": "424",
        "ChipID": "012B4567",
        "BACStatus": "TS_SUCCESS",
        "SACStatus": "TS_NOT_PERFORMED",
        "Data": "Test Line 1 >>>>>\nTest Line 2 >>>>>\nTest Line 3 >>>>>",
        "DocType": "PASSPORT",
        "DocNumber": "123456789",
        "DocID": "PASSPORT",
        "Surname": "Person",
        "Forename": "IMA Phoney",
        "SecondName": "J",
        "Nationality"     : "Imaging Automation Demo State",
        "Sex": "Male",
        "DOB": "12 May 70",
        "ExpiryDate": "01 Apr 12",
        "IssueState": "Passport Agency Billerica",
        "ExpiredFlag": false,
        "ImageSource": 0,
        "OptionalData1": "123456789123456",
            "OptionalData2": "",
            "DateOfIssue":"11 April 02",
            "PlaceOfBirth":"Illinois, U.S.A"
    }

    console.log("----------------->",data);

          var Fields = ({       
            IssueState,
            ExpiryDate,
            DateOfIssue,
            PlaceOfBirth,
            DOB,
            Sex,
            DocNumber,
            DocType
          } = data, {      
            IssueState,
            ExpiryDate,
            DateOfIssue,
            PlaceOfBirth,
            DOB,
            Sex,
            DocNumber,
            DocType
          })
          
          console.log("--------subset--------->",Fields);
Varun Sharma
  • 4,632
  • 13
  • 49
  • 103
  • @NickParsons Thanks For the comment, But I don't want to use ES-6. And I have attached solution also, But I want some othersolution. – Varun Sharma Sep 16 '19 at 11:07
  • Instead of another solution, is it not easier just to understand what is going on? – Amadeus Sep 16 '19 at 11:08
  • @Amadeus Thanks for comment. Could make easy this one. Means here I am confusing with double assignment. two time we assigning value =. Could more elaborate. – Varun Sharma Sep 16 '19 at 11:10
  • 1
    The first part is called [object destructuring](http://javascript.info/destructuring-assignment#object-destructuring). The second part, after [comma](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator), is creating a new object with those variable. And everything is between parenthesis to make sure is ran before the assignment – Amadeus Sep 16 '19 at 11:13

3 Answers3

2

There are multiple ways you can handle this case. Object destructuring as you have done in your example is one simple way. You can also use an array to store the required keys and write code as below

function subset(parentObj) {
  const keys = ['key1', 'key2', 'key3'];

  const obj = {};
  for (let i = 0, length = keys.length; i < length; i += 1) {
    obj[keys[i]] = parentObj[keys[i]];
  }

  return obj;
}

Or you can also use the above code with some functional programming

function subset(parentObj) {
  const keys = ['key1', 'key2', 'key3'];

  return keys.reduce((acc, key) => ({
    ...acc,
    [key]: parentObj[key];
  }), {});
}
S4beR
  • 1,872
  • 1
  • 17
  • 33
1

A simple to achieve what you are asking using ES5 is to create a list of all the properties you want to keep, and using Array#reduce add each property to a new object.

// Saves vertical space for example
var original = JSON.parse(`{"Checksum":"OK","ID":"012B4567","DOB":"12-12-1991","Data":"Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>","issue":"11-April-2015","DocID":"PASSPORT","Number":"123456789","Document":"PASSPORT","Photo":"Qk06AAAAAAAAA","ExpiredFlag":false,"ExpiryDate":"01 Apr 12","Forename":"IMA Phoney","Image2":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","ImageSource1":0,"Image3":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","Image1":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","IssueState":"USA","Nationality":"USA","PlaceOfBirth":"U.S.A","SecondName":"J","Sex":"Male","Surname":"XYZ"}`);

var propertiesToUse = ["ID", "Number", "Document", "IssueState", "Nationality", "PlaceOfBirth", "SecondName", "Sex", "Surname"];

var result = propertiesToUse.reduce(function(result, key) {
  return result[key] = original[key], result;
}, {});

console.log(result);
nick zoum
  • 7,216
  • 7
  • 36
  • 80
1

What you have done is a simple way, but if you are confused with it, you can divide it into two lines and explain it.

This line actually destrucutes your object and assign the value for the mentioned keys in the object to the corresponding variables.

{       
            IssueState,
            ExpiryDate,
            DateOfIssue,
            PlaceOfBirth,
            DOB,
            Sex,
            DocNumber,
            DocType
          } = data

Now, each of this variable has data individually, but we want it in an object. Therefore, we use the second part, i.e. creating an object with the following variable acting as keys.

{
        IssueState,
        ExpiryDate,
        DateOfIssue,
        PlaceOfBirth,
        DOB,
        Sex,
        DocNumber,
        DocType
      }

When combined you get the desired result in a single statement.

Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35