JavaScript array re structure

javascript map
javascript destructuring
javascript convert array to another array
javascript use map to modify array
javascript destructor
javascript transform array
javascript convert array to map
js transform array of objects

I have an array with student and parent addresses.

For example,

  const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];

I'm trying to reformat this to the following result.

const list = [
{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent: [
        {
            parent_address: 'USA',
            relationship:'mother'
        },{
            parent_address: 'Spain',
            relationship:'father'
        }
    ]
},
{
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent:[
        {
            parent_address: 'France',
            relationship:'father'
        }
    ]
}
];

So far I tried the following way. I'm not sure that is the right way or not.

const duplicateInfo = [];
for (var i = 0; i < user[0].length; i++) {
    var parent = [];
    if (duplicateInfo.indexOf(user[0][i].id) != -1) {
        // Do duplicate stuff
    } else {
        // Do other
    }
    duplicateInfo.push(user[0][i].id);
}

One approach would be to use .reduce() with an object as an accumulator. For each id, you can store an associated object with a parents array which you can append to in your .reduce() callback whenever you encounter a new object with the same id. Then to get an array of objects from your object, you can call Object.values() on it

See example below:

const users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' } ];
const res = Object.values(users.reduce((acc, {parent_address, relationship, ...r}) => { // use destructuring assignment to pull out necessary values
  acc[r.id] = acc[r.id] || {...r, parents: []}
  acc[r.id].parents.push({parent_address, relationship}); // short-hand property names allows us to use the variable names as keys
  return acc;
}, {}));

console.log(res);

Destructuring assignment, One of the most common tasks that developers perform in any language is taking an array of values and transforming those values. Up until recently, doing that in� For example, in JavaScript every object is an associative array. In fact it would be fairer to say that the associative array is the fundamental data structure in JavaScript and this is so powerful it can be used to implement object or just about any other data structure you care to think up. Really you don't need anything else.

You could reduce the array and search for a user with the same id and add the parent information to it.

If the user is not found, add a new user to the result set.

const
    users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' }],
    grouped = users.reduce((r, { parent_address, relationship, ...user }) => {
        var temp = r.find(q => q.id === user.id );
        if (!temp) r.push(temp = { ...user, parent: []});
        temp.parent.push({ parent_address, relationship });
        return r;
    }, []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Transforming Arrays with Array#map, The built in sort for arrays can do this. A caveat to this function is that, unlike filter, map, and other functions, this modifies the array you are sorting in place, instead � The call to new Array(number) creates an array with the given length, but without elements. The length property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods. If we shorten length manually, the array is truncated. We can use an array as a deque with the following operations:

Restructuring data like this is pretty common and Array.reduce() is designed for the task. It is a different way of viewing things and takes some getting used to, but after you write the code a few times it becomes second nature.

reduce() is called on an array and takes two parameters:

  1. a function that will be called for each element in the array
  2. the starting value

Your function then is called for each element with the the starting value for the first run or the return value from the previous function call for each subsequent run, along the array element, index into the original array, and the original array that reduce() was called on (the last two are usually ignored and rarely needed). It should return the object or whatever you are building up with the current element added, and that return value gets passed to the next call to your function.

For things like this I usually have an object to keep the unique keys (id for you), but I see you want an array returned. That's one line to map the object and keys to an array and it's more efficient to use the build-in object property mechanism instead of array.find() to see if you have added an id already.

const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];

let combined = users.reduce(
  // function called for each element in the array
  (previous, element) => {
    // previous starts out as the empty object we pass as the second argument
    // and will be the return value from this function for every other element
    
    // create an object for the id on our 'previous' object if it doesn't exist,
    // if it does exist we will trust the name, email, and age from the first
    // instance
    previous[element.id] = previous[element.id] || {
      id: element.id,
      name: element.name,
      age: element.age,
      parents: []
    };
    
    // now add parent
    previous[element.id].parents.push({
      parent_address: element.parent_address,
      relationship: element.relationship
    });
    
    // return our updated object, which will be passed to the next call
    // and eventually returned
    return previous;
  },
  {} // initial value is an empty object, no ids yet
);

// transform object into array with elements in order by key
let list = Object.keys(combined).sort().map(key => combined[key]);

console.dir(list);

Iterating Over and Reducing Data, This is more about JavaScript than the WordPress REST API, but it's kind of fun to do and a good example of Array.reduce : var data2 = data.reduce(function(list,� With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken.

You need to iterate twice using the current method. The complexity is O(n^2). (for Loop + indexOf)

A better way is index the array and use the array key for duplication detection and search.

For example:

const map = {};
users.forEach(user => {
    // Will return undefined if not exist
    let existing = map[user.id];
    if (!existing) {
        // If not exist, create new
        existing = {
            id: user.id,
            ...
            parents: [ {parent_address: user.parent_address, relationship: user.relationship ]
        }
    } else {
        // Otherwise, update only parents field
        // You can add other logic here, for example update fields if duplication is detected.
        existing.parents.push({parent_address: user.parent_address, relationship: user.relationship ]
        });
    }
    map[user.id] = existing;
})
// Convert the object to array
const list = map.values();

Restructure Objects coming from Rest-Api, Looking at my regular JavaScript code, I see that destructuring assignments are everywhere. Reading object properties and accessing array� The JavaScript Array class is a global object that is used in the construction of arrays; which are high-level, list-like objects. Description. Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed.

const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];
const updatedUsers = users.map(user => {
    return {
    id: user.id,
    name: user.name,
    email: user.email,
    age: user.age,
    parent: [{
        relationship: user.relationship,
        parent_address: user.parent_address,
    }]
}
})

const list = updatedUsers.reduce((acc, user) => {
    const findIndex = acc.findIndex(eachUser => eachUser.id === user.id && eachUser.email === user.email);
    if (findIndex < 0) {
        acc.push(user);
        return acc;
    } else {
    acc[findIndex].parent.push(user.parent);
    return acc; 
    }
}, []);
console.log(list)

5 Interesting Uses of JavaScript Destructuring, newColumnNames Array The new columns of the DataFrame. Examples df. restructure(['column1', 'column4', 'column2', 'column3'])� The real strength of JavaScript arrays are the built-in array properties and methods: Examples var x = cars.length; // The length property returns the number of elements

API Reference � dataframe-js, Its additions really improve the coding experience in JavaScript and once again shows that JavaScript is here to stay. One of the new features is� JavaScript provides many functions that can solve your problem without actually implementing the logic in a general cycle. Let's take a look. Find an object in an array by its values - Array.find. Let's say we want to find a car that is red. We can use the function Array.find. let car = cars.find(car => car.color === "red");

ES6: Destructuring — an elegant way of extracting data from arrays , Restructure allows you to declaratively encode and decode binary data. An Array maps to and from a JavaScript array containing instances of a sub-type. Removing Elements from End of a JavaScript Array. JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.

How to restructure an array of strings based on prefix, Loop for(val of Object.values(obj)) to iterate over object values: Object.values returns an array of them. Recursive structures. A recursive (recursively-defined) data structure is a structure that replicates itself in parts. We’ve just seen it in the example of a company structure above. A company department is: Either an array of people.

Comments
  • So in short - to make it easier for future readers - you want to combine parent_address and relationship in to a parent object, and merge them when a duplicate name and email address are found.
  • How parent address can be taken? What property should be used to relate them? Thanks in advance!:)
  • The code snippet at the end doesn't match the data structure. You say const list = [] at first, but at the bottom you iterate over that list apparently by iterating over user[0]. Your example code should be consistent.
  • @Lewis yes, I want exactly like you mentioned.
  • @SteUp, those value are retrieve it from my existing db and join with student and parent table. What I only have student's id in parent table.
  • Thanks, I will check details and I'm very existed to read your code.
  • Ooh this is solid. The object destructuring in the reduce callback is nice, but maybe a bit heavy for a beginner though.
  • The simpler version looks great!
  • Thank you so much. I read your code and easy to understand especially on second code snippet. Appreciate to other members' answer as well. Again, thank you so much guys.
  • Thanks, I will check details and I'm very existed to read your code.
  • An explanation would be in order. E.g., what did you change? And why?