Refactor array of objects

replace data value with object refactoring
what immediate benefit arises if you refactor array information into a class
refactoring guru
use of string constants as field names for use in data arrays
replace type code with subclasses
encapsulation refactoring
refactoring type code
introduce null object

The below code will have input as array of objects and I would like to convert into a different format.

The below code works fine but I need a more refactored shorter format of what I am trying to achieve.

var res =  {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1@yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton@yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);

var res = [];
for(var key in parsedObj.data){
    var emailObj = {};
    var phoneObj = {}
    if(parsedObj.data[key].email !== null){
        emailObj.matchedRes = parsedObj.data[key].email;
        emailObj.id = parsedObj.data[key].id;
        emailObj.type = "email";
        res.push(emailObj);
    }
    if(parsedObj.data[key].phone !== null){
        phoneObj.matchedRes = parsedObj.data[key].phone;
        phoneObj.id = parsedObj.data[key].id;
        phoneObj.type="phone";
        res.push(phoneObj);
    }  
}
console.log(res);

Desired output:

[ { matchedRes: 'jack1@yahoo.com', id: 'jack1', type: 'email' },
  { matchedRes: 'jack.clinton@yahoo.com', id: 'jack2', type: 'email' },
  { matchedRes: '+16464922600', id: 'jack2', type: 'phone' } ]

In the above code separate objects are created with phone and email for same id.

You can use reduce with destructuring assignment . and check if email or phone is there than add a object accordingly

var res =  {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1@yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton@yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);

let op = parsedObj.data.reduce((out,{id,email,phone})=>{
  if(email){
    out.push({matchedRes:email,id,type:`email`})
  } 
  if(phone){
  out.push({matchesRes:phone,id,type:`phone`})
  }
  return out
},[])

console.log(op)

Refactor array of objects, You can use reduce with destructuring assignment . and check if email or phone is there than add a object accordingly. var res� In other words, it is an array of map objects instead of an array of objects. If you're interested in this recent JavaScript feature, you should check out the MDN documentation on the Map data object. Whether you really want to use map objects or plain objects depends on your use case.

Here is a solution!

I just did a generic reducer, and then I use it on phone and email.

Then, I just spread the result of both calls to the result array :)

var res =  {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1@yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton@yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);

const extractData = (obj, type) => obj.reduce((acc, elt) => (
  elt[type] && acc.push({matchedRes: elt[type], id: elt.id, type: type})
, acc),[]);

const result = [...extractData(parsedObj.data, 'email'), ...extractData(parsedObj.data, 'phone')];

console.log(result);

Refactoring techniques, The refactoring techniques in this group streamline methods, remove code Change Reference to Value � Replace Array with Object � Duplicate Observed Data� Replace Array with Object. You have an array in which certain elements mean different things. Replace the array with an object that has a field for each element.

This should be possible with reduce:

var res =  {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1@yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton@yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
const keyFields = ["email", "phone"];

let result = parsedObj.data.reduce((acc, val) => {
    keyFields.forEach(k => {
       if (val[k]) acc.push({ matchedRes: val.email, id: val.id,  type: k});
    });
    return acc;
}, []);

console.log("Result: ", result);

Practical PHP Refactoring: Replace Array with Object, When to introduce an object where a simple array already works? A clue that points to the need for this refactoring in numerical arrays is the fact� If you have an array of objects that you need to sort into a certain order, you might be tempted to reach for a JavaScript library. But before you do, remember that you can do some pretty neat

If you are looking for a little shorter code but still easy to read for anybody:

var res =  {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1@yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton@yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);

var res = [];

Object.entries(parsedObj.data).forEach(el => {
    el = el[1]
    if(el.email !== null)
      res.push({
        matchedRes: el.email,
        id: el.id,
        type: "email"
      })
    if(el.phone !== null)
       res.push({
        matchedRes: el.phone,
        id: el.id,
        type: "phone"
    })
})

console.log(res);

Organizing Data: Replace Array with Object, Organizing Data: Replace Array with Object But as soon as any complexity rears its head, you should refactor them into 'real' objects. Problem: A class (or group of classes) contains a data field. The field has its own behavior and associated data. Solution: Create a new class, place the old field and its behavior in the class, and store the object of the class in the original class.

Replace Array with Object, Demonstrating the refactoring technique, Replace Array with Object with an example Source Duration: 5:47 Posted: Jun 30, 2012 Array Elements Can Be Objects. JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

Replace Array with Object, You have an array in which certain elements mean different things. Replace the array with an object that has a field for each element. Using something like a loop against an array or an object means you only have to write the HTML per item once time. Better still, any future edits only have to be applied once and only once. Like most power, it does come with some responsibility.

Refactoring: Extracting Data Objects - Qafoo GmbH, This already reveals the name for the data object to choose: class ProductCriteria { public $phrase; public $categories = array(); public� In PyCharm, you can simplify fragments of code in which you are getting multiple values out of an array or an objects using a dedicated refactoring, intention action, or quick-fix. Extract a destructuring. Position the caret at the value from an array or an object.

Comments
  • Seems pretty optimized to me :)
  • Read here hackernoon.com/…
  • Best not to abuse the conditional operator as a replacement for if. The conditional operator is when you need a resulting expression - if you don't need an expression, the conditional operator is not appropriate
  • I agree with you, it is often less readable and only appropriate in some cases. But as OP asked for a shorter format... :) I gave my best to the shortest version!
  • You can destructuring assignment to make it even shorted stackoverflow.com/questions/54605286/…
  • Thanks you for the overwhelming response. Learned lot of refactoring techniques with Reduce today.
  • @user804401 You should google something like javascript performance map vs reduce, but from my understanding, this will be quite the same. The performance will mainly depends on your mapping/reducing function, but in the end, both functions do the same: iterating on an array, executing the function to map/reduce, then adding the result of this function in a target object. Maybe reduce is slightly heavier (not even sure about that), but I think that when you come to that kind of fine tuning issue, you will probably want to modify your data model more than using something else than reduce!
  • You can destructuring assignment to make it even shorted stackoverflow.com/questions/54605286/…
  • I saw that it your answer. Nice solution!
  • The only slight issue with that is the OP wants the phone, email fields mapped to a matchedRes field, right?
  • Yeah, fixed that key naming mate. Thanks for pointing out miss