Compare array of objects with array - javascript

I have an array of objects:
arr1 = [
{
"id": 1,
"color": "blue",
"label": "School",
},
{
"id": 2,
"color": "red",
"label": "Work",
}
]
and a simple array:
arr2 = [ 2, 5 ]
I want to write a method that returns true if one of the object ids from arr1 can be found in arr2. So I could use it with
v-if
later.
What's your suggestion?

let arr1 = [
{
"id": 1,
"color": "blue",
"label": "School",
},
{
"id": 2,
"color": "red",
"label": "Work",
}
]
let arr2 = [ 2, 5 ]
let arr1_id = arr1.map(function (obj) {
return obj.id;
});
function check(array1, array2) {
let intersection = array1.filter(element => array2.includes(element));
if (intersection.length > 0) {
return true
}
else {return false}
}
bool = check(arr1_id,arr2)
console.log(bool)

Related

How can I inner join with two object arrays in JavaScript?

I need inner join with two array in javascript like this:
array1 =
[
{
"id": 1,
"name": "Tufan"
},
{
"id": 2,
"name": "Batuhan"
},
{
"id": 3,
"name": "Hasan"
}
]
array2 =
[
{
"name": "yyy",
"externalid": "1",
"value": "Asd"
},
{
"name": "aaaa"
"externalid": "2",
"value": "ttt"
}
]
expectedArray =
[
{
"id": 1,
"name": "Tufan",
"externalid": "1",
"value": "Asd"
},
{
"id": 2,
"name": "Batuhan",
"externalid": "2",
"value": "ttt"
}
]
rules:
on: array2.externalid = array1.id
select: array1.id, array1.name, array2.externalid, array2.value
My approach:
array1.filter(e => array2.some(f => f.externalid == e.id));
// I need help for continue
How can I make this?
Doesn't matter information: I use ES5 and pure javascript
You can do it like this:
const res = array2.map((item) => {
const related = array1.find((el) => el.id == item.externalid);
return { ...item, ...related };
});
Using a map to loop over the array2 and a find to get the array1 relative.

Returning parent key based on a value in a list of arrays in Javascript

{
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
This is list of arrays with keys and values as array, I want to return all the keys based on a particular value;
For Eg:
I want to return the parent keys which are [arr1,arr2], reason being both the arrays contain a value Unique, So I want to return the parent key of both the values, which is arr1 and arr2 respectively.
Note: The list can have n numbers of arrays.
Any help would be appreciated. Thanks in advance.
The simplest way to go about this is:
Loop through the keys in your object
Check if the array contains any objects with the name "Unique"
If so, add the objects key to an array
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
// Create our array that will contain the keys
const keys = []
// Loop through each key in the object
for (const prop in obj) {
// Use .some to see if any of the objects in this array have the selected name
const containsUnique = obj[prop].some(o => o.name === 'Unique')
if (containsUnique) {
// Add the current key to the array
keys.push(prop)
}
}
// Use the array of keys which contain an object named "Unique"
console.log(keys)
This is a more generic approach:
const getKeysByValue = (data, value) => {
const dataKeys = Object.keys(data);
const valueKey = Object.keys(value);
return dataKeys.filter(currKey => {
for(let element of data[currKey])
if(element[valueKey] === value[valueKey])
return true;
});
}
const data = {
"arr1":[
{
"name":"something1",
"shape": "Trapezium",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"shape": "Octagon",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"shape": "Square",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"shape": "Triangle",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"shape": "Circle",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"shape": "Triangle",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
}
],
"arr3":
[
{
"name":"Not-Unique",
"shape": "Circle",
"id":"8hcf14ee58ea25g343e9a2f208df215c"
}
]
}
console.log(getKeysByValue(data, {"name": "something2"})); // ["arr1"]
console.log(getKeysByValue(data, {"name": "Unique"})); // ["arr1", "arr2"]
console.log(getKeysByValue(data, {"shape": "Circle"})); // ["arr1", "arr3"]
console.log(getKeysByValue(data, {"shape": "Square"})); // ["arr1"]
The function receives two parameters, data and value. value is expected to be in the format of the value you are looking to filter with. In your example you wanted it to be "Unique" and in each object in the array it was presented like "name": "Unique" so we will send it as an object, {"name": "Unique"}.
In this way you can have different value to filter with. In the example above I added a shape key and value to each element, we can filter by this value too as shown in the example above.
you can do like this :
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
arr=[]
//loop over dict with pair keys and value
for (const [key, value] of Object.entries(obj)) {
//get the list of name from dict and check it if it contains Unique string
value.map(e=>e.name).includes("Unique") ? arr.push(key) : false
}
console.log(arr)
You can use array some method
const data = {
"arr1": [{
"name": "something1",
"id": "233111f4-9126-490d-a78b-1724009fa484"
},
{
"name": "something2",
"id": "50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name": "something4",
"id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name": "something5",
"id": "ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2": [{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
}]
}
var obj = [],
keys;
for (keys in data) {
data[keys].some(a => "Unique" === a.name) && obj.push(keys);
}
console.log(obj);
An alternative way that i could think of is using Regexp
var obj = {
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
let str = JSON.stringify(obj);
let match = str.matchAll(/\"([\w\d]+)\":\[(?:{[\s\S]+},)*{\"name\":\"Unique\"/g);
let parent = [];
for(let m of match){
parent.push(m[1]);
}

structuring obj array based on their attributes [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed 1 year ago.
can you help me with this problem with js\react?
I'm trying to manage 2 arrays due to obtain a new object based on their shared attribute (Array A: "id" and Array B: "parent")
I think isn't hard but I'm struggling to do it atm :(
Array A
[{
"id": "606f1a2bebb5fb53804dd3d5",
"name": "cc",
}, {
"id": "606f1a30cfe84430c41dce88",
"name": "bb",
}, {
"id": "606f1a4ed2ff554e4ea11b82",
"name": "ff",
}]
Array B
[{
"id": "3344",
"color": "pink",
"parent": "606f1a2bebb5fb53804dd3d5",
}, {
"id": "3453",
"color": "blue",
"parent": "606f1a30cfe84430c41dce88",
}, {
"id": "3331",
"color": "yellow",
"parent": "606f1a4ed2ff554e4ea11b82",
}, {
"id": "4442",
"color": "black",
"parent": "606f1a30cfe84430c41dce88",
}]
I want merge these two arrays and create a new one where the array B objects are split by "id" of array A.
Something like this:
[{
"606f1a2bebb5fb53804dd3d5": [{
"id": "3344",
"color": "pink",
"parent": "606f1a2bebb5fb53804dd3d5",
}]
}, {
"606f1a30cfe84430c41dce88": [{
"id": "3453",
"color": "blue",
"parent": "606f1a30cfe84430c41dce88",
}, {
"id": "4442",
"color": "black",
"parent": "606f1a30cfe84430c41dce88",
}]
}, {
"606f1a4ed2ff554e4ea11b82": [{
"id": "3331",
"color": "yellow",
"parent": "606f1a4ed2ff554e4ea11b82",
}]
}]
Thanks very much guys
You just need array b for grouping and another object for keeping track of the max key inside of a group.
const
data = [{ id: "3344", color: "pink", parent: "606f1a2bebb5fb53804dd3d5" }, { id: "3453", color: "blue", parent: "606f1a30cfe84430c41dce88" }, { id: "3331", color: "yellow", parent: "606f1a4ed2ff554e4ea11b82" }, { id: "4442", color: "black", parent: "606f1a30cfe84430c41dce88" }],
max = {},
result = data.reduce((r, o) => {
max[o.parent] = (max[o.parent] || 0) + 1;
(r[o.parent] ??= {})[max[o.parent]] = o;
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think you can loop through the items and then find the parent
let arrayC = [];
arrayB.forEach(item => {
let parent = array1.find(e => e.id === item.parent);
// do something here to combine it into one object
// then arrayC.push(newItem);
});
https://codesandbox.io/s/boring-snowflake-brksj?file=/src/index.js
const result = arrayA.reduce((acc, arrayAItem) => {
return {
...acc,
[arrayAItem.id]: arrayB.filter(
(arrayBItem) => arrayBItem.parent === arrayAItem.id
)
};
}, {});
}]
You can do this with map and filter functions of array.
const newArray = array1.map(array1Item => {
return { [array1Item.id]: array2.filter(array2Item => array2Item.parent === array1Item.id)}
})
Based on the two arrays that you have, I assume that they are only linked by their "parent" ids. If this is the case, you can reduce the B array using the A array as an accumulator.
const a = [
{ "id": "606f1a2bebb5fb53804dd3d5" , "name": "cc" },
{ "id": "606f1a30cfe84430c41dce88" , "name": "bb" },
{ "id": "606f1a4ed2ff554e4ea11b82" , "name": "ff" },
];
const b = [
{ "id": "3344" , "color": "pink" , "parent": "606f1a2bebb5fb53804dd3d5" },
{ "id": "3453" , "color": "blue" , "parent": "606f1a30cfe84430c41dce88" },
{ "id": "3331" , "color": "yellow" , "parent": "606f1a4ed2ff554e4ea11b82" },
{ "id": "4442" , "color": "black" , "parent": "606f1a30cfe84430c41dce88" },
];
const c = Object
.entries(b.reduce((acc, { id, color, parent }) =>
({ ...acc, [parent]: {
...acc[parent],
colors: [...acc[parent].colors, { id, color } ]
}}),
Object.fromEntries(a.map(({ id, name }) =>
[ id, { name, colors: [] } ]))))
.map(([ id, value ]) => value);
console.log(c);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Convert JSON Array to a JSON Object using Javascript

I would like to know how to convert the input json array to a json object in the expected format using Javascript
Here is my input array
[
{
"Id": 1,
"Name": "One"
},
{
"Id": 2,
"Name": "Two"
},
{
"Id": 3,
"Name": "Three"
}
]
Expected json object output
{ "1" : "One",
"2" :"Two",
"3" :"Three"
}
You can use array reduce and pass an empty object in the accumulator. Then inside the reduce callback update the accumulator array by adding key and value
let obj = [{
"Id": 1,
"Name": "One"
}, {
"Id": 2,
"Name": "Two"
}, {
"Id": 3,
"Name": "Three"
}]
let newObj = obj.reduce(function(acc, curr) {
acc[curr.Id] = curr.Name;
return acc;
}, {})
console.log(newObj)
let arr = [{
"Id": 1,
"Name": "One"
},
{
"Id": 2,
"Name": "Two"
},
{
"Id": 3,
"Name": "Three"
}
]
let json1 = {}
for (const s of arr) {
json1[s.Id] = s.Name
}
console.log(json1)
You only need a simple for loop to iterate trough the array and then assign new properties to the resulting object, like so:
let array = [{ "Id": 1, "Name": "One"}, {"Id": 2, "Name": "Two"}, {"Id": 3, "Name": "Three"}];
let obj = {};
for (let i = 0; i < array.length; i++) {
const elem = array[i];
obj[elem.Id] = elem.Name;
}
console.log(obj);
Iterate over the array of objects, use Object.values() to get the values for each object and then create new obects using the first value as the key.
var arr = [ { "Id": 1, "Name": "One" }, { "Id": 2, "Name": "Two" }, { "Id": 3, "Name": "Three" } ];
var jsonObj = {};
arr.forEach(function(item){
var values = Object.values(item);
jsonObj[values[0]] = values[1];
})
console.log(jsonObj); // gives {"1": "One","2": "Two","3": "Three"}

copying data from one array to another array

Array One:
array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}]
Array Two:
array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}]
Resulting Array:
resultingArray = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}],
"a_id" : {"id": 5, "name": "bcd"}
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}],
"a_id" : {"id": 4, "name": "bef"}
}]
I am looking to add the array2 objects into array1 based on id's of array2. I have tried using map function on both the arrays to compare and add the object but I didn't succeed. Can you please suggest me how to do it?
Thank you
Add the array2 objects into array1 based on ids of array2.
let array1 =
[
{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}
];
let array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}
];
let resultingArray=[];
array1.forEach(function(element) {
element['a_id'] = [];
element['attr'].forEach(function(attr) {
element['a_id'].push(array2.find(function(item) {
return item.id == attr.value;
}));
});
resultingArray.push(element)
});
console.log(resultingArray);
I presume you intend to extract the object whose ID is equal to the value field the in the each object in array1.
var array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}];
var array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}];
var resultingArray = [];
for(var i = 0; i < array1.length; i++) {
resultingArray[i] = array1[i];
for(var j = 0; j < array2.length; j++) {
if(resultingArray[i].attr[0].attr_code.value === array2[j].id) {
resultingArray[i].push("a_id": array2[j]);
}
}
}
You just need to lop through array1, and for each object in array1, you need to find corresponding objects in array2 which match the criterion.
You can use array map and array index to do:
var array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}];
var array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}];
var result = array1.map(current=>{
//find index of attr in array2
let index = array2.findIndex(c=>{
if (c['id']===(Number(current['attr'][0]['value'])))
return c;
});
current["a_id"] = array2[index];
return current;
});
console.log(result);
Please check if the following code suites your requirement. You may need to make some changes.
function mergeArrays3 (arr1, arr2) {
return arr1.map((value, index) => {
let object = null;
let result = {...value};
for (let element of arr2) {
if (element.id == parseInt(value.attr[0].value)) {
object = element;
break;
}
}
if (object != null) {
let attr = value.attr[0];
if (attr.hasOwnProperty("attr")) {
result[value.attr[0].attr] = object;
} else if (attr.hasOwnProperty("attr_code")) {
result[value.attr[0].attr_code] = object;
}
}
return result;
});
}
I loop over first array and find an element in second array matching id of value.attr[0].value. If found then i added this object in the first array at key of value.attr[0].attr or value.attr[0].attr_code.
I have tried using map function on both the arrays to compare and add
the object but I didn't succeed
Below is the functional programming approach using map():
/* GIVEN */
const array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{
"attr_code": "a_id",
"value": "5"
}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{
"attr": "a_id",
"value": "4"
}]
}
]
const array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}]
/* From array2, make an object keyed by the 'id' field. We'll use this as a key-value lookup table */
const lookupTable = array2.reduce((accum, item) => {
accum[item.id.toString()] = item
return accum
}, {})
console.log('***LOOKUP TABLE***\n', lookupTable) // result is an object we use to lookup
/* From array1, we append data from the lookup table */
const final = array1.map(item => {
item.a_id = lookupTable[item.attr[0].value]
return item
})
console.log("***RESULT***\n", final)
Hope this helps.
Cheers,

Categories

Resources