best way to merge 2 disparate data sets in javascript? [duplicate] - javascript

This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 1 year ago.
What's the best way to merge 2 disparate data sets in javascript? For example,
const parentRecords = [{
id: 1,
mycol1: 'parent name',
}]
const childRecords = [{
childid: 2,
parentId: 1,
mycol2: 'child name',
}]
const mergedRecords = [...parentRecords, ...childRecords]
This code returns an array where each of the records above exist as separate rows. I need the result to look like this:
[{
id: 1,
mycol1: 'parent name',
childid: 2,
parentId: 1,
mycol2: 'child name',
}]

You didn't specify on which criteria items should be merged. In my answer I'm assuming it's based on the parent id and the children parentId:
const parentRecords = [{
id: 1,
mycol1: 'parent name',
}];
const childRecords = [{
childid: 2,
parentId: 1,
mycol2: 'child name',
}];
const result = parentRecords.map((x) =>
Object.assign(
x,
childRecords.find((y) => y.parentId === x.id)
)
);
console.log(result);

Related

Retrieve all values from json array that match a variable value

I have a html select element with options(categories). Upon selecting an option(category) I get the option's value and store it in a variable.
const currentSelectValue = $('option:selected', this).attr('value');
I also have a JSON array with all subcategories.
const myObjArr = {
data: [
{ id: 1, name: 'name_1', parent_id: '1' },
{ id: 2, name: 'name_2', parent_id: '2' },
{ id: 1, name: 'name_2', parent_id: '3' }
]
};
My goal is to get the selected option value and match it to the list of subcategories, find the parent_id(which is the value from the selected option) and list all the results.
I'm new to JavaScript, so a detailed answer with an example would be much, much appreciated. Thanks in advance!
Check this out JS .filter()
Assume you have 3 in your parent_id. Here is one line clean code solution
const myObjArr = {
data: [{
id: 1,
name: 'name_1',
parent_id: '1'
},
{
id: 2,
name: 'name_2',
parent_id: '2'
},
{
id: 1,
name: 'name_2',
parent_id: '3'
}
]
};
// if parent id is 3
const currentSelectValue = 3
const selected = myObjArr.data.filter((ele,index) => ele.parent_id == currentSelectValue
)
console.log(selected)

What is the most effective way to filter this array? [duplicate]

This question already has answers here:
How to get the difference between two arrays of objects in JavaScript
(22 answers)
Closed 1 year ago.
I have two arrays. My goal is to get a third array with users that exist in usersUpdated but do not exist in oldUsers. I know i have to apply multiple filters, but I do not know how.
const oldUsers = [
{ name: 'Fede', id: 1 },
{ name: 'Marce', id: 2 },
];
const usersUpdated = [
{ name: 'Fede', id: 1 },
{ name: 'Marce', id: 2 },
{ name: 'Ale', id: 3 },
{ name: 'Julian', id: 4 },
];
const expectedValue = [
{ name: 'Ale', id: 3 },
{ name: 'Julian', id: 4 }
];
Convert arrays to objects, use names as keys & ids as values, delete keys of old obj from updated obj then convert the updated obj back to array.

How can i improve this filter ? this is working but i think that isnt the right way [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have those object arrays and it has to be a better way to to this, this filter is supposed to return only the items on the first array that contains the same name in the second array but only with those pre determined status
const Array1 = [
{ id: 1, name: 'test1', status: 'STATUS1' },
{ id: 2, name: 'test2', status: 'STATUS2' },
{ id: 3, name: 'test3', status: 'STATUS3' },
{ id: 4, name: 'test4', status: 'STATUS4' }
];
const Array2 = [
{ id: 1, name: 'test1' },
{ id: 2, name: 'test2' },
{ id: 3, name: 'test3' }
];
let filteredOrders = Array1.filter(m =>
Array2.find(s => s.name === m.name) && m.status.includes("STATUS1", "STATUS2")
)
console.log(filteredOrders)
I would consider breaking this down into two separate steps:
Create an hash of existing names in Array2 to compare against (so you don't have to loop through it multiple times)
const names = Array2.reduce(function(map, obj) {
map[obj.name] = true;
return map;
}, {});
Then do your filtering:
const matching = Array1.filter( m =>
names[m.name] && ["STATUS1", "STATUS2"].includes(m.status)
)
Also, a small note of distinction between the way you filtered by status and the way I did.
You wrote: m.status.includes("STATUS1", "STATUS2") which does a string based matching. Basically, do any of these values appear (entirely or in-part) in the string I'm trying to match.
Which would mean that a record with a status value of "STATUS12" would return true since "STATUS1" appears in "STATUS12".
The version I provided uses array based includes() using the statuses you're trying to find as the array and doing a direct comparison against each status you're trying to match.
First, Let's fix the code
.includes() can not take 2 inputs for searching in a string, the second parameter is used for specifying an offset, We'll replace this with match and a regex /STATUS[1-2]/
m.status.includes("STATUS1", "STATUS2")
// becomes
m.status.match(/STATUS[1-2]/)
A better way to achieve what you're after is to create an array of names, and then just do 1 loop over the array that needs filtering.
const Array1 = [
{ id: 1, name: 'test1', status: 'STATUS1' },
{ id: 2, name: 'test2', status: 'STATUS2' },
{ id: 3, name: 'test3', status: 'STATUS3' },
{ id: 4, name: 'test4', status: 'STATUS4' }
];
const Array2 = [
{ id: 1, name: 'test1' },
{ id: 2, name: 'test2' },
{ id: 3, name: 'test3' }
];
// make an array that contains only the name value from each object in Array2
const Array2Names = Array2.map(i => i.name)
// filter Array1
let filteredOrders = Array1.reduce((a, i) => {
if (Array2Names.includes(i.name) && i.status.match(/STATUS[1-2]/)) return [...a, i]
else return a
}, [])
console.log(filteredOrders)
/* [
{
"id": 1,
"name": "test1",
"status": "STATUS1"
},
{
"id": 2,
"name": "test2",
"status": "STATUS2"
}
] */

To destructure a particular property of each object that is nested in an array of objects [duplicate]

This question already has answers here:
Destructuring array of objects in es6
(5 answers)
Closed 1 year ago.
I'm wondering if I can destructure this array of objects
const course = {
id: 1,
name: 'Half Stack application development',
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
},
]
}
and save the property exercises in a variable, I dont know if we would ever do this, just want to know how and if we can destructure object properties in an array of objects
#ggrlen Here's the array
const arr = [{
name: 'State of a component',
exercises: 14,
id: 3
}];
I want to destruct the object in this array, to extract value of exercises property into a variable, thanks for the reply btw.
Converting my comments into an answer to illustrate various destructuring patterns:
const course = {
id: 1,
name: 'Half Stack application development',
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
},
]
};
console.log(course.parts.map(e => e.exercises));
console.log(course.parts.map(({exercises: e}) => e)); // rename to `e`
let {parts: [{exercises}]} = course; // extract nested property
console.log(exercises); // 10
({parts: [,{exercises}]} = course); // second elem
console.log(exercises); // 7
({parts: [,,{exercises}]} = course); // third elem
console.log(exercises); // 14
const arr = [
{
name: 'State of a component',
exercises: 14,
id: 3
},
{
name: 'State of a component',
exercises: 1422,
id: 3
}
];
const [{exercises}] = arr;
console.log(exercises); // 14
let [, ...rest] = arr; // extract everything after the first
console.log(rest);
// from second elem, extract `exercises` as `ex`,
// extract object properties other than `exercises` as `others`
const [,{exercises: ex, ...others}] = arr;
console.log(ex); // 1422
console.log(others);

Inserting a unique id into a multidimensional object

I have an object with this structure (imagine it could be way bigger than this)
And I need to insert a new item inside, say, 'Name 3' children array. How would I go about creating a unique id for it? I have thought about saving the ids inside the object in a separate array and then creating one that is not on that, but I'd have to maintain it and I'm not sure that would be the best approach?
let obj = {
id: 1,
name: 'Name 1',
parent_id: null,
children: [{
id: 2,
name: 'Name 2',
parent_id: 1,
children: []
},
{
id: 3,
name: 'Name 3',
parent_id: 1,
children: [{
id: 4,
name: 'Name 4',
parent_id: 3,
children: []
}]
}
]
};
EDIT: The need for a unique id is for me to be able to delete an item. This is the code I've been given to work with, I can't alter the structure.

Categories