Skip to content
Advertisement

I have a mixed type of array object. I need to split it as per type

I have a array object with mixed type of key values. i need to separate it with type of key value pair.

[
  {
    TOOL_PM: "ETX29405-PM1",
    fcbmaxsum: 223.49,
    fcbmaxsumperfeat: 74.5,
    numfeat: 3
  },
  {
    TOOL_PM_x: "ETX29304-PM7",
    TOOL_PM_y: "ETX29304-PM7",
    fcbmax: 289.76,
    fcmax: 2.03,
    globalSelection: "No",
    innerSelection: "No",
    variable: "AdjustedPressure_Step1_SKW"
  },
  {
    TOOL_PM: "ETX29405-PM2",
    fcbmaxsum: 260.49,
    fcbmaxsumperfeat: 8.5,
    numfeat: 2
  },
  {
    TOOL_PM_x: "ETX29304-PM1",
    TOOL_PM_y: "ETX29304-PM1",
    fcbmax: 209.76,
    fcmax: 1.04,
    globalSelection: "No",
    innerSelection: "No",
    variable: "ChamberManometerAdjustedPressure_Step1_SKW"
  }
]

I need to split it the above object separately as per type. as like below

Array Object 1

[
  {
    TOOL_PM: "ETX29405-PM1",
    fcbmaxsum: 223.49,
    fcbmaxsumperfeat: 74.5,
    numfeat: 3
  },
  {
    TOOL_PM: "ETX29405-PM2",
    fcbmaxsum: 260.49,
    fcbmaxsumperfeat: 8.5,
    numfeat: 2
  }
] 

Array Object 2

[
  {
    TOOL_PM_x: "ETX29304-PM7",
    TOOL_PM_y: "ETX29304-PM7",
    fcbmax: 289.76,
    fcmax: 2.03,
    globalSelection: "No",
    innerSelection: "No",
    variable: "AdjustedPressure_Step1_SKW"
  },
  {
    TOOL_PM_x: "ETX29304-PM1",
    TOOL_PM_y: "ETX29304-PM1",
    fcbmax: 209.76,
    fcmax: 1.04,
    globalSelection: "No",
    innerSelection: "No",
    variable: "ChamberManometerAdjustedPressure_Step1_SKW"
  }
]

As like above. I need to achieve it by java script. I have tried it with forEach condition. but i am not achieve the result. Thanks in Advance.

Advertisement

Answer

First, you need to be able to check if the object is of type A or type B.

For instance :

let o = {
    TOOL_PM: "ETX29405-PM1",
    fcbmaxsum: 223.49,
    fcbmaxsumperfeat: 74.5,
    numfeat: 3
};

function isTypeA(ob) {
    return typeof ob.TOOL_PM !== 'undefined';
} 

function isTypeB(ob) {
    return typeof ob.TOOL_PM_x !== 'undefined';
} 

Here, I decided to check the existence of the property TOOL_PM or TOOL_PM_x. But it’s a business decision that you have to make.

Then, you iterate thought the array, check the current object and put it in the right output array :

let all = [ /* ... */];
let allTypeA = [];
let allTypeB = []; 
all.forEach(o => {
    if(isTypeA(o)) {
        allTypeA.push(o);
    } else if(isTypeB(o)) {
        allTypeB.push(o);
    } else {
        /* Warning : unknown object type */
    }
}); 

When you reach a programming issue, break it into simpler things. Rewriting your issue with other inputs sometimes helps to resolve it.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement