0

I'm new to nodejs and currently trying to write a function in lambda, I have a query from a SQL database that gives me objects from fields with different schema. I need all those values to return as string if they are not null.

This works but it's just too much repetition. Do you know any better way, using foreach on Object.values.. or function etc.. I just can't get it right.

 a var Result = [];
 var item =  results.map(dataField) => {
     dataField.es_id  == null ? "" : dataField.es_id = dataField.es_id.toString();
     dataField.status  == null ? "" : dataField.status = dataField.status.toString();
     dataField.er_Act  == null ? "" : dataField.er_Act = dataField.er_Act.toString();

     Result.push(dataField);


});
callback(null, Result );
1
  • 1
    Shouldn't dataField.es_id == null ? "" : dataField.es_id = dataField.es_id.toString(); be dataField.es_id == null ? "" : dataField.es_id.toString();? Commented Feb 27, 2019 at 4:57

2 Answers 2

1

Iterate over all properties

a var Result = [];
var item = results.map(dataField) => {
  for (var property in dataField) {
      if (dataField.hasOwnProperty(property)) {
          dataField[property] = dataField[property] === null ? "" : dataField[property].toString()
      }
  }

  Result.push(dataField);
});
callback(null, Result );
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this looks pretty close to what I'm after, the problem is it turns (null ) to ( "" ), is there a way to keep null properties intact? ..as null
@adimona why not?) Just put null or dataField[property] instead of "". Same result, null just shorter in this case.
@adimona, are you sure about the syntax in the code?
1

You need to assign to the property of dataField for the empty string to be properly put on the object, otherwise your "" in

dataField.es_id  == null ? "" :

is just an unused expression.

To reduce code repetition, iterate over an array of properties:

const Result = [];
results.forEach((dataField) => {
  ['es_id', 'status', 'er_Act'].forEach((prop) => {
    dataField[prop] = dataField[prop] === null
    ? ''
    : dataField[prop].toString();
  });
  Result.push(dataField);
});

Or, if every property value on the object needs to be replaced, there's no need to hard-code the property names, and you can generate the result more functionally by iterating over the Object.entries of the input:

const Result = results.map((dataField) => (
  Object.entries(dataField).reduce((a, [key, val]) => {
    a[key] = val === null
    ? ''
    : val.toString();
    return a;
  }, {})
));

Comments

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.