map two array of object by common value js - javascript

const object1: [{
"code": "lap-143240121",
"index": 0
}, {
"code": "lap-15040293",
"index": 1
}, {
"code": "lp-1504444",
"index": 2
}, {
"code": "lp-150440987",
"index": 3
}]
const object2: [{
"code": "lap-143240121",
"name": "name1"
}, {
"code": "lap-15040293",
"name": "name2"
}, {
"code": "lp-1504444",
"name": "name3"
}]
I would like to map those two list of object by code to have an output like :
const objectResult: [{
"code": "lap-143240121",
"index": 0,
"name": "name1"
}, {
"code": "lap-15040293",
"index": 1,
"name": "name2"
}, {
"code": "lp-1504444",
"index": 2,
"name": "name3"
}]

Use map to iterate object2 and then use rest operator to return an object which consist of all the elements and the name from object1
const object1 = [{
"code": "lap-143240121",
"index": 0
}, {
"code": "lap-15040293",
"index": 1
}, {
"code": "lp-1504444",
"index": 2
}, {
"code": "lp-150440987",
"index": 3
}]
const object2 = [{
"code": "lap-143240121",
"name": "name1"
}, {
"code": "lap-15040293",
"name": "name2"
}, {
"code": "lp-1504444",
"name": "name3"
}];
const obj3 = object2.map((item) => {
return {
...item, // will consist all the items from object2
// get index from object1 where the code matches
index: object1.find(elem => elem.code === item.code).index
}
});
console.log(obj3)

transform the object1 to Map with value of code as key and whole object as value
iterate on object2 search code from object2 in the above created map, if found merge the properties

Related

How to filter and access child element from nested array of objects in Javascript

I have the following array of objects and I would like to get the innermost child attribute if it matches the outer condition:
My condition should be if objArray.displayValue matches "display2" and its types.displayValue matches "inner_display4" then return its value, which is 4.
objArray = [
{
"name": "abc",
"displayValue": "display1",
"types": [
{
"name": "name1",
"displayValue": "inner_display1",
"value": "1"
},
{
"name": "name2",
"displayValue": "inner_display2",
"value": "2"
},
{
"name": "name3",
"displayValue": "inner_display3",
"value": "3"
}
]
},
{
"name": "cdf",
"displayValue": "display2",
"types": [
{
"name": "name4",
"displayValue": "inner_display4",
"value": "4"
},
{
"name": "name5",
"displayValue": "inner_display5",
"value": "5"
},
{
"name": "name6",
"displayValue": "inner_display6",
"value": "6"
}
]
}
]
You can try something like this
const find = (data, displayValue, innerDisplayValue) =>
data.reduce((res, item) => {
if(res || item.displayValue !== displayValue) return res
const type = item.types.find(t => t.displayValue === innerDisplayValue)
return type? type.value: res
}, undefined)
const objArray = [{
"name": "abc",
"displayValue": "display1",
"types": [{
"name": "name1",
"displayValue": "inner_display1",
"value": "1"
}, {
"name": "name2",
"displayValue": "inner_display2",
"value": "2"
}, {
"name": "name3",
"displayValue": "inner_display3",
"value": "3"
}]
}, {
"name": "cdf",
"displayValue": "display2",
"types": [{
"name": "name4",
"displayValue": "inner_display4",
"value": "4"
}, {
"name": "name5",
"displayValue": "inner_display5",
"value": "5"
}, {
"name": "name6",
"displayValue": "inner_display6",
"value": "6"
}]
}]
console.log(find(objArray, 'display2', 'inner_display4'))
console.log(find(objArray, 'display2', 'inner_display40'))
You could try the following:
First find the object that has the correct displayValue and then filter the types to return the object you're looking for. Once you have the correct types object destructure the value.
The const displayValue is your result
Hope the code is a little bit clear :)
const findByDisplayValue = (dv) => objArray.find((obj) => obj.displayValue === dv);
const { types } = findByDisplayValue('display2');
const getType = (typeValue) => types.filter((type) => type.displayValue === typeValue);
const [{ displayValue }] = getType('inner_display4');

Combine arrays into objects depending on elements

I have two arrays, Array 1 containing the sections, and Array 2 containing the objects, the goal is to insert the objects from Array 2 inside the objects into Array1 depending on the type (Sides or Sauces), for example: Each object from Array 2 containing the element type:Sauces should be set in an array inside the object of Array 1 with type:Sauces and so on. I tried by using the forEach function but since I'm relatively new to JavaScript I don't know how to proceed
Array 1 (Sections)
Array [
Object {
"required": false,
"type": "Sides",
},
Object {
"required": true,
"type": "Sauces",
},
]
Array 2 (List of Objects)
Array [
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
this is what I'm trying to achieve:
Array [
Object {
"required": false,
"type": "Sides",
"data": [
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
},
Object {
"required": true,
"type": "Sauces",
"data":[
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
]
},
]
this should work for you:
arr1.forEach((a,i) => {
a["data"] = arr2.filter(b => b.type == a.type);
})
I name Array1 = categories
I name Array2 = elements
You need to map on each.
const test = categories.map((cat) => {
elements.map((el) => {
if (el.type === cat.type) {
cat.elements.push(el);
}
return el;
});
return cat;
});
console.log(test);

Reduce it array to an easier way to map

I'm developing an application and have added new items to my array: type and description.
array = [
{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item1",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item1",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
},
]
I previously did this to reduce it down to an easier way to map it:
items = array.reduce((acc, e) => {
if (!acc[e["item"]["name"]]) {
acc[e["item"]["name"]] = {
[e["date"]["name"]]: e["price"]
}
} else {
acc[e["item"]["name"]][e["date"]["name"]] = e["price"]
}
return acc
}, {})
To show the data before I did
const dates = [...new Set(Object.keys(items_dicc).map(i => Object.keys(items_dicc[i])).flat())]
{
Object.keys(items_dicc).map((item) => {
return (
<tr>
<td>{item}</td>
{dates.map((date) => <td>{items_dicc[item][date] || ''}</td>)}
</tr>
)
})
}
I need to add the description element and type.name to the above. For example for description:
description: e["description"]
To display the elements as in the table:
ITEM
DESCRIPTION
TYPE
202001
202002
I1
item1
type1
100
200
I2
item3
type2
-
300
How do I add and show?
EDIT: console.log(items_dicc[item])
{202001: 100, 202002: 200, description: "item1", type: "type1"}
202001: 100
202002: 200
description: "item1"
type: "type1"
__proto__: Object
{202002: 300, description: "item3", type: "type2"}
202002: 300
description: "item3"
type: "type2"
__proto__: Object
You can add the description and type attribute inside the reduce method like this,
array = [
{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item2",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item3",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
},
]
items = array.reduce((acc, e) => {
if (!acc[e["item"]["name"]]) {
acc[e["item"]["name"]] = {
[e["date"]["name"]]: e["price"],
'description': e['description'],
'type': e.type?.name,
}
} else {
acc[e["item"]["name"]][e["date"]["name"]] = e["price"]
}
return acc
}, {})
console.log(items);
To add the for description and name in the table,
const dates = [...new Set(Object.keys(items_dicc).map(i => Object.keys(items_dicc[i])).flat())]
{
Object.keys(items_dicc).map((item) => {
return (
<tr>
<td>{item}</td>
<td>{items_dicc[item]?.description}</td>
<td>{items_dicc[item]?.type}</td>
{dates.map((date) => <td>{items_dicc[item][date] || ''}</td>)}
</tr>
)
})
}
I have been seeing your question regarding these type of tables from yesterday. You have posted several questions with similar things. I suggest you to read some article and understand how JS array methods works instead of asking incremental questions in SO.
Asking in SO might solve your problems for now, but in the long run you will suffer as you don't seem to have a grip on how these things works.
you can simplify your solution like this.
const array = [{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item2",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item3",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
}
]
const result = array.map(item => {
return Object.keys(item).reduce((a, c) => {
if (c === "date") {
a[item[c].name] = item.price;
} else if (c !== "price" && c !== "id") {
a[c] = (typeof item[c] === "object") ? item[c].name : item[c];
}
return a;
}, {})
});
console.log(result);

how to compare the key in the array of object and modify it using javascript

I have two objects obj1 and obj2, how to loop through array key children and if code name matches, then add the name key in the object obj2, get the object.
How to loop through object of objects and match the key and push the key to get the new object in javascript
function newObject(obj1, obj2) {
var result = obj1.map(e => {
if ('children' in e)
e.children = e.children.map(child => {
if ('children' in child)
child.children = child.children.map(c => {
name: c.name
});
return child;
});
return e;
})
return result
}
var obj1 = [{
"id": 1,
"item": "node1",
"children": [{
"id": 2,
"code": "countries",
"title": "Country",
"children": [{
"cid": 12,
"code": "S1",
"name": "SG",
"children": [{
"id": 4,
"code": "C1",
"name": "City"
}]
},
{
"cid": 13,
"code": "S2",
"name": "TH"
}
]
},
{
"id": 2,
"code": "Groceries",
"title": "Grocery",
"children": [{
"cid": 11,
"code": "G1",
"name": "Fruits"
},
{
"cid": 10,
"code": "G2",
"name": "Vegetables"
}
]
}, {
"id": 3,
"code": "lists",
"title": "Option"
}
]
}];
var obj2 = [{
id: 1,
code: "G1",
status: "active"
},
{
id: 2,
code: "S2",
status: "inactive"
},
{
id: 3,
code: "C1",
status: "active"
}
];
console.log(this.newObject(obj1, obj2));
Expected Output
[
{id:1, name: "Fruits",code:"G1", status:"active"},
{id:2, name: "TH",code:"S2", status:"inactive"},
{id:3, name: "city",code:"C1", status:"active"}
]
you can check this code
I fixed your object and you can find your expectation in the console

Merge two objects when there's a new key

I have two objects with the following structure and tried to merge them together.
I tried it with $.merge but its not the expected result.
Object 1 - Has not all attributes
{
"id": 23,
"name": "Article",
"related": 15 "items": [{
"name": "Test1",
"items": [{
"name": "Test2",
"items": [{
"name": "Test3",
"items": [{
"name": "Test4",
"items": [{
"name": "Test5",
"items": [{
"name": "Test6",
}]
}]
}]
}]
}]
}]
}, {
"id": 24…
}
Object 2 - with additional attributes
{
"id": 23,
"name": "Article",
"related": 15 "items": [{
"name": "Test1",
"id": 34 "items": [{
"name": "Test2",
"id": 57 "items": [{
"name": "Test3",
"id": 92 "items": [{
"name": "THIS ONE IS NOT EXISTING IN OBJECT 1 AND SHOULD NOT GET MERGED",
"id": 789
}, {
"name": "Test4",
"id": 12 "items": [{
"name": "Test5",
"id": 321 "items": [{
"name": "Test6",
"id": 285
}]
}]
}]
}]
}]
}]
}, {
"id": 24…
}
Does anyone know some smart trick? Is jQuery even necessary?
jQuery's $.extend will do what you want.
//merging two objects into new object
var new_object = $.extend(true, {}, object1, object2);
//merge object2 into object1
$.extend(true, object1, object2);
The 1st parameter: deep:true, see: https://api.jquery.com/jquery.extend/
Without jquery: https://jsfiddle.net/sLhcbewh/
function mymerge_sub(object1, object2)
{
for(var i in object2) {
if(i == 'items')
continue;
console.log(i);
if(object1[i] === undefined) {
console.log(i + ' not found');
object1[i] = object2[i];
}
}
if(object1.items !== undefined) {
mymerge_sub(object1.items[0], object2.items[0])
}
}
function mymerge(object1, object2) {
var ret = JSON.parse(JSON.stringify(object1));
mymerge_sub(ret, object2); // save obj 1
return ret;
}
var obj3 = mymerge(obj1, obj2);
If you want several items, you have to loop mymerge_sub(object1.items[j]... ).

Categories