0

My object demoList:

demoList = [
    {
      id: 1,
      validFrom: "2019-06-01T00:00:00",
      validTo: "2020-06-17T00:00:00",
      xxxM: 50,
      xxxN: 2.2,
      xxxQ45: 2,
      xxxQ100: 1.65,
      xxxQ125: null,
      xxxQ150: null,
      xxxQ250: null,
      xxxQ300: null,
      xxxQ500: null
    },
     {
      id: 2,
      validFrom: "2019-06-01T00:00:00",
      validTo: "2020-06-17T00:00:00",
      xxxM: 51,
      xxxN: 22,
      xxxQ45: 1.4,
      xxxQ100: 1.65,
      xxxQ125: null,
      xxxQ150: 1.7,
      xxxQ250: null,
      xxxQ300: 0.15,
      xxxQ500: null,
      xxxQ700: 15.4
    },
   . . .
];

The array I want to obtain:

["M", "N", "45", "100", "150", "300", "700"]

I want an array of non-empty values starting with xxx and found in the demoList list. How do I do this using angular?

1 Answer 1

1

You can .flatMap() your demoList objects to the Object.entries() of each object. You can keep only those entries which start with "xxx" and the value doesn't equal null by using .filter(). You can then map each key to either the last suffix number on the key or the last character of the key using .match(/\d+|\w$/g). You can then put this mapped array into a new Set() to remove any duplicates. Then you can spread ... this set into an array to convert the set back into an array:

const demoList = [{ id: 1, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 50, xxxN: 2.2, xxxQ45: 2, xxxQ100: 1.65, xxxQ125: null, xxxQ150: null, xxxQ250: null, xxxQ300: null, xxxQ500: null }, { id: 2, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 51, xxxN: 22, xxxQ45: 1.4, xxxQ100: 1.65, xxxQ125: null, xxxQ150: 1.7, xxxQ250: null, xxxQ300: 0.15, xxxQ500: null, xxxQ700: 15.4 } ];

const res = [...new Set(
  demoList.flatMap(Object.entries)
          .filter(([k, v]) => k.startsWith("xxx") && v !== null)
          .map(([k]) => k.match(/\d+|\w$/g).pop())
)];

console.log(res);

Sign up to request clarification or add additional context in comments.

3 Comments

trying with stackblitz "ERROR Error: (intermediate value).slice is not a function" error
@devedev I am not using .slice() in my code, sounds like an unrelated issue
How can I optimize this code ` let barems: String[] = []; this.demoList.forEach(list=> { let keys: string[] = Object.getOwnPropertyNames(list); keys.forEach(key => { if(key.includes("xxx") && list[key] != null){ if(barems.indexOf(key) == -1){ barems.push(key); console.log(key); } } }) }) `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.