Kevin.a
Kevin.a

Reputation: 4296

Reduce returns undefined with condition

I have a string that a parse to a JSON object. Now i want to check for every object key if it contains a certain sub string. In that case I want to add it to my accumulated object. Somehow i keep getting undefined.

Here's the code :

const myString = '{ "Address__c": "3QAO", "Id": "OxWQAU", "Address__r": { "Address_Line_1__c": "kjj", "Address_Line_2__c": "kl", "Country__c": "United States", "State__c": "California", "Id": "a022M00001aJIW3QAO", "CountryLabel": "United States", "StateLabel": "California" } }';

const parsed = JSON.parse(myString);
const nameSpace = 'NameSpace__';

const newObj = Object.keys(parsed).reduce((acc,curr) => {

    if(curr.includes('__c')){
        return {...acc , [nameSpace + curr] : parsed[curr]};
    }


},{})

console.log(newObj)

EDIT:

So adding an else gives me the following result :

{ NameSpace__Address__c: '3QAO' }

How can it be that just one key is altered. When there's more than 1 containing this '__c' string

Upvotes: 0

Views: 71

Answers (3)

Iiskaandar
Iiskaandar

Reputation: 394

Reduce function gives you only one object (for example sum of every objects), you should use 'filter' to get list of your wanted objects.

Upvotes: 0

claasic
claasic

Reputation: 1050

Besides adding else { return acc }, there is a reason your result only includes a single key.

Your parsed object is:

{ Address__c: '3QAO',
  Id: 'OxWQAU',
  Address__r: 
   { Address_Line_1__c: 'kjj',
     Address_Line_2__c: 'kl',
     Country__c: 'United States',
     State__c: 'California',
     Id: 'a022M00001aJIW3QAO',
     CountryLabel: 'United States',
     StateLabel: 'California' } }

So that means Object.keys(parsed) is:

[ 'Address__c', 'Id', 'Address__r' ]

So those are your possible curr values.

From here you can go either with a recursive approach if you want to add the nested keys too or you flatten the structure beforehand.

A unclean recursive solution would look something like:

const myString = '{ "Address__c": "3QAO", "Id": "OxWQAU", "Address__r": { "Address_Line_1__c": "kjj", "Address_Line_2__c": "kl", "Country__c": "United States", "State__c": "California", "Id": "a022M00001aJIW3QAO", "CountryLabel": "United States", "StateLabel": "California" } }';

const parsed = JSON.parse(myString);
const nameSpace = 'NameSpace__';

const newObj = parsed => Object.keys(parsed).reduce((acc,curr) => {

    if (parsed[curr] instanceof Object) {
      return {...acc, ...newObj(parsed[curr])}
    }
    
    if(curr.includes('__c')) {
        return {...acc , [nameSpace + curr] : parsed[curr]};
    } else {
      return acc;
    }

},{})

console.log("result: ", newObj(parsed))

Upvotes: 2

eledgaar
eledgaar

Reputation: 778

yeah! maybe adding else { return acc }

Upvotes: 1

Related Questions