Igal
Igal

Reputation: 4783

filter object by property in nodejs

My object looks like that :

    {
    "performance": {...},
    "a": "",
    "b": "N",
    "c": true,
    "groups": [
      {
        "acctTypes": [
          {
            "xxx": "xxx",
            "ttt": "ttt",
            "accounts": [
            {
              ...
            },
            {
              ...
            },
            {
              ...
            }
            ],
          },
          {
            "acctTypes": [
              {
                "xxx": "xxx",
                "ttt": "ttt",
                "accounts": [
                  {
                    ...
                  },
                  {
                    ...
                  },
                  {
                    ...
                  },
                  {
                    ...
                  },
                  {
                    ...
                  }
                ],
              },
    ],
    "summary": [
      {
        ...
      },
      {
        ...
      }
    ]
}

I'm trying to pull all the "accounts" from it (looked into _js and lodash - but couldn't find anything relevant)

the result should be an object / array which contains all the accounts

Any help will be appreciated.

Thanks

Upvotes: 2

Views: 435

Answers (1)

Evya
Evya

Reputation: 2375

If the obj is structured in a similar way further down, this might work for you

obj = {
	"performance": {},
	"a": "",
	"b": "N",
	"c": true,
	"groups": [
	{
		"acctTypes": [
			{
				"xxx": "xxx",
				"ttt": "ttt",
				"accounts": [
					{
						a:1
					},
					{
						b:2
					}
				],
			},
			{
				"acctTypes": [
					{
						"xxx": "xxx",
						"ttt": "ttt",
						"accounts": [
							{
								c:3
							},
							{
								d:4
							}
						],
					},
				],
				"summary": [
					{

					},
					{
					}
				]
			}]}]}

let filtered = obj.groups.reduce(key => key.accounts).acctTypes
let accounts = []
filtered.map(key => {
	if (key.accounts) {
		accounts.push(...key.accounts)
	} else if (key.acctTypes){
		accounts.push(...key.acctTypes[0].accounts)
	}
})
console.log(accounts)

I've added data to accounts for some PoC. I test whether each item in filtered contains an accounts key or an acctTypes which in turn should include an accounts key, then add the values to the accounts array using ES6 spreading.

Upvotes: 1

Related Questions