Combine javascript objects from an array that contain almost similar key - javascript

I have an array that contains objects. The array looks like this:
[
{
"number": "10a",
"person": "Velvet"
},
{
"number": "10b",
"person": "Edna"
},
{
"number": "11a",
"person": "Shionne"
},
{
"number": "11b",
"person": "Aifread"
},
]
I want to combine objects that have identical number property. For example, the first two objects have property number: "10a", and number: "10b". I want these to be combined such that the output becomes:
{
"10": {
"person": ["Velvet", "Edna"]
},
"11": {
"person": ["Shionne", "Aifread"]
}
}
I am not sure how to do it as it seems too complicated for me. I also looked over stackoverflow but can't seem to find a similar problem, hence, my post. Thanks for the help!

I'll assume that the normalization for number is just to remove non numeric characters. If so, you can just iterate over the original array and process each element:
var original = [
{
"number": "10a",
"person": "Velvet"
},
{
"number": "10b",
"person": "Edna"
},
{
"number": "11a",
"person": "Shionne"
},
{
"number": "11b",
"person": "Aifread"
},
];
const merged = {}
original.forEach(item => {
var normalizedKey = item.number.replaceAll( /\D/g, "" )
if(!merged[normalizedKey]) merged[normalizedKey] = { person: []}
merged[normalizedKey].person.push(item.person)
})
console.log({merged})

Parse number. Add object if missing and append name:
const result = {};
arr.forEach(o => {
const nr = o.number.slice(0,2);
result[nr] = result[nr] || {person:[]};
result[nr].person.push(o.person);
});
console.log(result);

Related

javascript how to replace data where id match

I have a data like this in array.
[
{
"teamName": "TeamA",
"players": ["1","2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
]
and I want to replace players id which match in other array
players = [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}
]
So output will be like this
[
{
"teamName": "TeamA",
"players": [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}]
},
{
"teamName": "TeamB",
"players": [
{
"id": "2",
"playername": "john"
}]
}
]
I tried to find by for loop and where it will find and replace but that's not working for me.
you can do this by iterating over first array and updating the players property of each element in that array.
let arrOne = [
{
"teamName": "TeamA",
"players": ["1","2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
]
players = [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}
]
// solution
arrOne.forEach( teamObject => {
let newPlayerArray = [];
teamObject.players.forEach( id => {
let newPlayerObject = {};
newPlayerObject.id = id;
newPlayerObject.playername = players.find( player => player.id == id)?.playername;
newPlayerArray.push(newPlayerObject)
})
teamObject.players = newPlayerArray;
})
One approach:
// defining the variables, naming 'teams' as it was unnamed in
// the original post:
let teams = [
{
"teamName": "TeamA",
"players": ["1", "2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
],
// updated the name of this Array of Objects due to the naming
// clash between the original name ('players') when using
// destructuring assignments while iterating the 'teams' Array,
// because of an identically-named property:
playerDetails = [{
"id": "1",
// I updated this property-name to use camelCase consistently:
"playerName": "alex"
},
{
"id": "2",
"playerName": "john"
}
],
// rather than editing the original Array, we create a new one
// by iterating over the teams Array, using Array.prototype.map():
combined = teams.map(
// using destructuring assignement to retrieve the named properties
// of the Object passed in to the function:
({
teamName,
players
}) => {
// because we're returning an Object literal, we have to use return and wrap
// the anonymous callback function of the Arrow function in curly braces ('{...}')
// to avoid the returned Object-literal being misinterpreted as a function body:
return {
// we return the teamName property unchanged:
teamName,
// but here we update the players property, we iterate over the players Array,
// again using players.prototype.map() to update the existing Array based on the
// result of actions taken in the anonymous Arrow function:
players: players.map(
// we pass in a reference to the 'id' enclosed within the player Array,
// giving it a verbose/clear name given that 'id' would be a sensible/short
// name, but is used within the enclosed function as the named property of
// the other function we're working with.
// within the anonymous function we use Array.prototype.find():
(teams_playerID) => playerDetails.find(({
// passing in a reference to the 'id' property-name of the Object
// within the playerDetails Array:
id
// and here we check to see if the 'id' of the playerDetails Array is
// exactly-equal to the teams_playerID variable; if so this Object is
// returned and the 'players' Array is updated, and changed from a String
// to the found Object; if no match is found the current 'players' Array-value
// is unchanged:
}) => id == teams_playerID ))
}
});
console.log(combined);
// [{"teamName":"TeamA","players":[{"id":"1","playerName":"alex"},{"id":"2","playerName":"john"}]},{"teamName":"TeamB","players":[{"id":"2","playerName":"john"}]}]
JS Fiddle demo.
References:
Array.prototype.find().
Array.prototype.map().
Arrow functions.
Destructuring assignemnt.
You can build the result by stepping through the list of teams, looking up each player by their id, and adding the player record to the result’s players array.
const teams = [
{
"teamName": "TeamA",
"players": ["1", "2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
]
const players = [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}
]
let result = []
teams.forEach(team => {
let record = {
"teamname": team.teamName,
"players": []
}
team.players.forEach(player_id => {
record.players.push(players.find(p => p.id === player_id))
})
result.push(record)
})
console.log(JSON.stringify(result, null, 4))

How to push values to an object from inside a map function when a condition is met?

How can we push values to an object from inside a map function and return that single object. I have string comparison condition inside the map function. I tried using Object.assign but it returns an array with multiple object inside that array. Instead of this multiple object I'm expecting a single object inside an array.
Map function
let arrayObj = arrayToTraverse.map(function(item) {
var myObj = {};
if(item.inputvalue === 'Name'){
Object.assign(myObj, {name: item.value});
} else if (item.inputvalue === 'Email'){
Object.assign(organizerInfo, {email: item.value});
} else if (item.inputvalue === 'Company'){
Object.assign(organizerInfo, {company: item.value});
}
return myObj;
});
console.log("The array object is", arrayObj)
This return the array of objects as follows
[
{
"name": "Tom"
},
{
"email": "tom#abc.com"
},
{
"company": "ABC"
}
]
But The array I'm expecting is
[
{
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
// or
[
"returned": {
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
An example of arrayToTraverse can be considered as following
[
{
"id": "1",
"inputvalue": "Name",
"value": "Tom",
"type": "Short Text"
},
{
"id": "2",
"inputvalue": "Email",
"value": "tom#abc.com",
"type": "Email ID"
},
{
"id": "3",
"inputvalue": "Company",
"value": "Google",
"type": "Long Text"
}
]
Simply put, you're trying to reduce an array to a single object, not map one array to another.
var arrayToTraverse = [
{inputvalue:"Name",value:"Tom"},
{inputvalue:"Email",value:"tom#abc.com"},
{inputvalue:"Company",value:"ABC"},
{inputvalue:"Foo",value:"Bar"} // wont show up
];
var valuesRequired = ["Name","Email","Company"];
var result = arrayToTraverse.reduce( (acc, item) => {
if(valuesRequired.includes(item.inputvalue))
acc[item.inputvalue.toLowerCase()] = item.value;
return acc;
}, {});
console.log(result);
Edit: Added lookup array for required fields.

Problems extracting property names from an object (JAVASCRIPT)

I have an array of objects (I think!) and I need to extract the property name (for example "nickname") from a given object.
With
var VarObjAndValue = newArr[0];
I get the individual arrays (for example Object { nickname: “jhonny” }).
How can I now extract the property name "nickname" from the object above?
Listing the keys with
var listPropertyNames = Object.keys(newArr);
only provides sequential numbers from 0 to 6 rather than the desired keys names..
var StrToInclude = ["nickname", "name", "surname", "sex", "dob", "email", "phone"];
var newArr=[]; //Key name + its value
for (var i=0; i<StrToInclude.length; i++) {
temp_obj = {};
temp_obj[StrToInclude[i]] = document.getElementById(StrToInclude[i]).value;
newArr.push(temp_obj);
}
console.log('newArr --> = ',newArr);
/**
* newArr = [
* { "nickname": “jhonny” },
* { "name": “jonathan” },
* { "surname": “ross” },
* { "sex": “male” },
* { "dob": “22/02/1984” },
* { "email": “j#yahoo.com” },
* { "phone": "123" }
* ]
*/
var VarObjAndValue = newArr[0];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=0 ----> Object { nickname: “jhonny” }
var VarObjAndValue = newArr[1];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=1 ----> Object { name: "jonathan" }
var listPropertyNames = Object.keys(newArr);
console.log('listPropertyNames --> = ',listPropertyNames); //Array(7) [ "0", "1", "2", "3", "4", "5", "6" ] (not useful for this...)
newArr.map(obj => Object.keys(obj)).flat()
or newArr.map(obj => Object.keys(obj)[0])
or from dave's comment
newArr.reduce((keys, o) => [...keys, ...Object.keys(o)], [])
gives you all property names as an array
Not sure if this is what you want, but you have already gotten those property names in StrToInclude
const newArr =
[
{
"nickname": "jhonny"
},
{
"name": "jonathan"
},
{
"surname": "ross"
},
{
"sex": "male"
},
{
"dob": "22/02/1984"
},
{
"email": "j#yahoo.com"
},
{
"phone": "123"
}
]
console.log(newArr.map(obj => Object.keys(obj)[0]))
You are very close to getting the right answer. Since newArr is an Array, the keys are numeric keys. All you have to do is go through each element is the Array of Objects to extract the keys. Something like this should do nicely:
for(let i = 0;i<newArr.length;i++){
console.log(Object.keys(newArr[i])); //Will go through the whole array and give you the keys of every object in it
}
You can simply do by looping over the array and using destructuring operator with the desired property name.
const arr = [
{
nickname: "abdullah"
},
{
age: 27
}
];
arr.forEach(({nickname}) => {
if (nickname) {
console.log(`Thats the property we want to extract: ${nickname}`);
break; // if you are not expecting this property name in other objects, otherwise no need to break
}
});

Reverse Traverse a hierarchy

I have a hierarchy of objects that contain the parent ID on them. I am adding the parentId to the child object as I parse the json object like this.
public static fromJson(json: any): Ancestry | Ancestry[] {
if (Array.isArray(json)) {
return json.map(Ancestry.fromJson) as Ancestry[];
}
const result = new Ancestry();
const { parents } = json;
parents.forEach(parent => {
parent.parentId = json.id;
});
json.parents = Parent.fromJson(parents);
Object.assign(result, json);
return result;
}
Any thoughts on how to pull out the ancestors if I have a grandchild.id?
The data is on mockaroo curl (Ancestries.json)
As an example, with the following json and a grandchild.id = 5, I would create and array with the follow IDs
['5', '0723', '133', '1']
[{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
},
There is perhaps very many ways to solve this, but in my opinion the easiest way is to simply do a search in the data structure and store the IDs in inverse order of when you find them. This way the output is what you are after.
You could also just reverse the ordering of a different approach.
I would like to note that the json-structure is a bit weird. I would have expected it to simply have nested children arrays, and not have them renamed parent, children, and grandchildren.
let data = [{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
}]
}]
}]
const expectedResults = ['5', '0723', '133', '1']
function traverseInverseResults(inputId, childArray) {
if(!childArray){ return }
for (const parent of childArray) {
if(parent.id === inputId){
return [parent.id]
} else {
let res = traverseInverseResults(inputId, parent.parents || parent.children || parent.grandchildren) // This part is a bit hacky, simply to accommodate the strange JSON structure.
if(res) {
res.push(parent.id)
return res
}
}
}
return
}
let result = traverseInverseResults('5', data)
console.log('results', result)
console.log('Got expected results?', expectedResults.length === result.length && expectedResults.every(function(value, index) { return value === result[index]}))

How to delete object from an array of objects having relations with each arrays?

This Object have relationship as: childOne > childTwo > childThree > childFour > childFive > childSix.
{
"parentObj": {
"childOne": [
{
"name": "A",
"id": "1"
},
{
"name": "B",
"id": "2"
}
],
"childTwo": [
{
"name": "AB",
"parent_id": "1",
"id": "11"
},
{
"name": "DE",
"parent_id": "2",
"id": "22"
}
],
"childThree": [
{
"name": "ABC",
"parent_id": "22",
"id": "111"
},
{
"name": "DEF",
"parent_id": "11",
"id": "222"
}
],
"childFour": [
{
"name": "ABCD",
"parent_id": "111",
"id": "1111"
},
{
"name": "PQRS",
"parent_id": "111",
"id": "2222"
}
],
"childFive": [
{
"name": "FGRGF",
"parent_id": "1111",
"id": "11111"
},
{
"name": "ASLNJ",
"parent_id": "1111",
"id": "22222"
},
{
"name": "ASKJA",
"parent_id": "1111",
"id": "33333"
}
],
"childSix": [
{
"name": "SDKJBS",
"parent_id": "11111",
"id": "111111"
},
{
"name": "ASKLJB",
"parent_id": "11111",
"id": "222222"
}
]
}
}
Is there any way to delete an item by ID and the objects which are associated with that particular ID should get deleted(i.e., If I do delete parentObj.childTwo[1], then all the related object beneath it should also gets deleted).
Looping manually is too bad code, and generate bugs. There must be better ways of dealing with this kind of problems like recursion, or other.
The data structure does not allow for efficient manipulation:
By nature objects have an non-ordered set of properties, so there is no guarantee that iterating the properties of parentObj will give you the order childOne, childTwo, childThree, ... In practice this order is determined by the order in which these properties were created, but there is no documented guarantee for that. So one might find children before parents and vice versa.
Although the id values within one such child array are supposed to be unique, this object structure does not guarantee that. Moreover, given a certain id value, it is not possible to find the corresponding object in constant time.
Given this structure, it seems best to first add a hash to solve the above mentioned disadvantages. An object for knowing a node's group (by id) and an object to know which is the next level's group name, can help out for that.
The above two tasks can be executed in O(n) time, where n is the number of nodes.
Here is the ES5-compatible code (since you mentioned in comments not to have ES6 support). It provides one example call where node with id "1111" is removed from your example data, and prints the resulting object.
function removeSubTree(data, id) {
var groupOf = {}, groupAfter = {}, group, parents, keep = { false: [], true: [] };
// Provide link to group per node ID
for (group in data) {
data[group].forEach(function (node) {
groupOf[node.id] = group;
});
}
// Create ordered sequence of groups, since object properties are not ordered
for (group in data) {
if (!data[group].length || !data[group][0].parent_id) continue;
groupAfter[groupOf[data[group][0].parent_id]] = group;
}
// Check if given id exists:
group = groupOf[id];
if (!group) return; // Nothing to do
// Maintain list of nodes to keep and not to keep within the group
data[group].forEach(function (node) {
keep[node.id !== id].push(node);
});
while (keep.false.length) { // While there is something to delete
data[group] = keep.true; // Delete the nodes from the group
if (!keep.true.length) delete data[group]; // Delete the group if empty
// Collect the ids of the removed nodes
parents = {};
keep.false.forEach(function (node) {
parents[node.id] = true;
});
group = groupAfter[group]; // Go to next group
if (!group) break; // No more groups
// Determine what to keep/remove in that group
keep = { false: [], true: [] };
data[group].forEach(function (node) {
keep[!parents[node.parent_id]].push(node);
});
}
}
var tree = {"parentObj": {"childOne": [{"name": "A","id": "1"},{"name": "B","id": "2"}],"childTwo": [{"name": "AB","parent_id": "1","id": "11"},{"name": "DE","parent_id": "2","id": "22"}],"childThree": [{"name": "ABC","parent_id": "22","id": "111"},{"name": "DEF","parent_id": "11","id": "222"}],"childFour": [{"name": "ABCD","parent_id": "111","id": "1111"},{"name": "PQRS","parent_id": "111","id": "2222"}],"childFive": [{"name": "FGRGF","parent_id": "1111","id": "11111"},{"name": "ASLNJ","parent_id": "1111","id": "22222"},{"name": "ASKJA","parent_id": "1111","id": "33333"}],"childSix": [{"name": "SDKJBS","parent_id": "11111","id": "111111"},{"name": "ASKLJB","parent_id": "11111","id": "222222"}]}}
removeSubTree(tree.parentObj, "1111");
console.log(tree.parentObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sure, the function you use to delete an entry should FIRST recurse, which means run itself on the linked entry, unless there is none. So, in psuedocode
function del(name, index)
{
if parent[name][index] has reference
Then del(reference name, reference ID)
Now del parent[name][index]
}
No loop needed.
And since we stop if there is no reference, we do not recurse forever.
Not sure what it is you want but maybe this will work:
const someObject = {
"parentObj": {
"childOne": [
{
"name": "A",
"id": "1"
},
{
"name": "B",
"id": "2"
}
],
"childTwo": [
{
"name": "AB",
"childOne": "1",
"id": "11"
},
{
"name": "DE",
"childOne": "2",
"id": "22"
}
]
}
};
const removeByID = (key,id,parent) =>
Object.keys(parent).reduce(
(o,k)=>{
o[k]=parent[k].filter(
item=>
!(Object.keys(item).includes(key)&&item[key]===id)
);
return o;
},
{}
);
const withoutID = Object.assign(
{},
someObject,
{ parentObj : removeByID("childOne","1",someObject.parentObj) }
);
console.log(`notice that childTwo item with childOne:"1" is gone`);
console.log("without key:",JSON.stringify(withoutID,undefined,2));
const otherExample = Object.assign(
{},
someObject,
{ parentObj : removeByID("childOne","2",someObject.parentObj) }
);
console.log(`notice that childTwo item with childOne:"2" is gone`);
console.log("without key:",JSON.stringify(otherExample,undefined,2));
const both = Object.assign(
{},
someObject,
{ parentObj : removeByID("childOne","1",otherExample.parentObj) }
);
console.log(`notice that childTwo items with childOne are both gone`);
console.log("without key:",JSON.stringify(both,undefined,2));

Categories

Resources