Iterate array of objects with string array [duplicate] - javascript

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 2 years ago.
I have an array of objects (JAVASCRIPT) like below
[
{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
},
{
"code": "980",
"label": "joe"
}
]
And i have a string array like below
["123", "234"]
I want to loop through array of objects and pass string array to get the "label"
I am expecting an output like below
[
{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
}
]
Please let me know if there is any efficient solution (JAVASCRIPT) because my array of objects is big.

Try this:
const obj = [
{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
},
{
"code": "980",
"label": "joe"
}
];
const arr = ["123", "234"];
var output = arr.flatMap(item => obj.filter(x => x.code == item));
console.log(output);

If the array is big, this can help to use Array.reduce.
const input = [{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
},
{
"code": "980",
"label": "joe"
}
]
const input2 = ["123", "234"];
const inputObj =input.reduce((acc, cur) => {
acc[cur.code] = cur.label;
return acc;
}, {});
const result = input2.reduce((acc, cur) => {
if (inputObj[cur]) {
acc.push({
code: cur,
label: inputObj[cur]
});
}
return acc;
}, []);
console.log(result);

Related

How to compare and manipulate json object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
I need to compare and manipulate JSON objects.
First object
let data1 = {
"id": "111",
"entity_id": "222",
"text_id": "333",
"details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving"
}]
}
Second object
let data2 = [{
"id": "111",
"text_id": "333",
"criteria_type": "TXT",
"value": 1000,
"comp": {
"id": "444",
"name": "driving"
}
}, {
"id": "222",
"text_id": "444",
"criteria_type": "TXT",
"value": 2000,
"comp": {
"id": "555",
"name": "swiming"
}
}]
There are 2 objects data1 and data2. Here, I need to compare the data1.details array with the data2 array key => data1.details.comp_id with data2.comp.id if not match then I need to push value, id and name to data1 object. Please help me to resolve this issue.
Resulting object
data1 will be:
{
"id": "111",
"entity_id": "222",
"text_id": "333",
"declaration_details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving",
}, {
"value": 2000,
"comp_id": "555",
"CompName": "swiming",
}]
}
Based on your expected result, wouldn't you just need to map data2 to the declaration_details of the resulting object?
const main = () => {
const { details, ...rest } = data1;
const result = {
...rest,
fbp_year: new Date().getUTCFullYear(),
declaration_details: data2.map(({
value,
comp: {
id: comp_id,
name: CompName
}
}) => ({
value,
comp_id,
CompName
}))
};
console.log(result);
};
const
data1 = {
"id": "111",
"entity_id": "222",
"text_id": "333",
"details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving"
}]
},
data2 = [{
"id": "111",
"text_id": "333",
"criteria_type": "TXT",
"value": 1000,
"comp": {
"id": "444",
"name": "driving"
}
}, {
"id": "222",
"text_id": "444",
"criteria_type": "TXT",
"value": 2000,
"comp": {
"id": "555",
"name": "swiming"
}
}];
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }
Use filter() to find objects in the data2 matching comp.id. Then you can just use map() to create a new array. Finally, you can add the mappedData2 array to the data1 in declaration_details.
let filteredData2 = data2.filter(item => {
return data1.details.some(detail => detail.comp_id === item.comp.id);
});
let mapData = filteredData2.map(item => {
return {
value: item.value,
comp_id: item.comp.id,
CompName: item.comp.name
};
});
You can use JSON.stringify(yourJsonObject) to convert your objects to strings.
Then you can compare them like this. areEqual = string1 == string2. Make sure the object properties are in the same order for both objects.

JS map generates double square brackets [duplicate]

This question already has answers here:
Copy array items into another array
(19 answers)
Closed 10 months ago.
I use the following to merge sub-arrays:
var myArray = [
{
"QuestionId": 1,
"mySeries": [{ "name": "Male", "data": [1] }],
"mySeries1": [
{ "name": "Male", "data": [0] },
{ "name": "Female", "data": [0] },
{ "name": "Unknown", "data": [0] }
],
"mySeries3": []
},
{
"QuestionId": 2,
"mySeries": [{ "name": "Banana", "data": [1] }],
"mySeries1": [
{ "name": "Orange", "data": [0] },
{ "name": "Banana", "data": [0] },
{ "name": "None", "data": [0] }
],
"mySeries3": []
}
];
var res = [];
for (let i = 0; i < myArray.length; i++) {
res = myArray[i].mySeries1.map(obj => myArray[i].mySeries.find(o => o.name === obj.name) || obj);
myArray[i].mySeries3.push(res);
It works; however, I get double square brackets:
"mySeries3": **[** [
{ "name": "Orange", "data": [0]},
{ "name": "Banana","data": [1]},
{"name": "None", "data": [0]
] **]**
Is push the correct way?
I used #pilchard `
myArray[i].mySeries3 = myArray[i].mySeries3.concat(res)
It worked.`

how to group JSON objects from array of JSON objects?

Here is an array of JSON objects that has array values that I want to group by (pull unique):
let myArray = [
{
"_id": "1",
"subdata": [
{
"subid": "11",
"name": "A"
},
{
"subid": "12",
"name": "B"
}
]
},
{
"_id": "2",
"subdata": [
{
"subid": "12",
"name": "B"
},
{
"subid": "33",
"name": "E"
}
]
}
]
Finally I need to get:
[
{
"subid": "11",
"name": "A"
},
{
"subid": "12",
"name": "B"
},
{
"subid": "33",
"name": "E"
}
]
I've tried lodash with no success:
let newArray = lodash.uniqBy(lodash.concat(myArray, 'subdata.subid'), '_id');
Of course I can scan each array element one by one but thought there is easy way to do it with lodash
Use _.flatMap() to get the an array of all subdata items, and then use _.uniqueBy() with subid:
const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];
const result = _.uniqBy(_.flatMap(myArray, 'subdata'), 'subid');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
With lodash/fp you can generate a function using _.flow() with the same methods:
const fn = _.flow(
_.flatMap('subdata'),
_.uniqBy('subid')
);
const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];
const result = fn(myArray);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>

Comparing arrays of objects and remove duplicate [duplicate]

This question already has answers here:
Remove duplicates in an object array Javascript
(10 answers)
Closed 5 years ago.
I have an array containing arrays of objects which I need to compare.
I've looked through multiple similar threads, but I couldn't find a proper one that compares multiple arrays of objects (most are comparing two arrays of objects or just comparing the objects within a single array)
This is the data (below is a JSFiddle with code sample)
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
I want to remove all duplicate arrays of objects, regardless of the length of data (there could be a lot more records).
I managed to get the unique ones extracted into an object:
const unique = data.reduce(function(result, obj) {
return Object.assign(result, obj)
}, [])
That doesn't work for me though, because I need 1 of the duplicated arrays to remain and the returned data to be an array as well, instead of an object. E.g.:
// result I need
[
[
{
"id":"65",
"name":"Some object name",
"value":90
},
{
"id":"89",
"name":"Second Item",
"value":20
}
],
[
{
"id":"14",
"name":"Third one",
"value":10
}
]
]
So how do I compare each array of objects to the others in the parent array and preserve one of each duplicated or unique array of objects?
JSFiddle
you can achieve so by using function.As below. Not sure about best optimum way of doing so.
var testArray = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
function removeDuplicatesFromArray(arr){
var obj={};
var uniqueArr=[];
for(var i=0;i<arr.length;i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = arr[i];
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
];
const temp = {};
const result = [];
data.forEach(itemArr => {
const items = itemArr.filter(item => {
const isUnique = temp[`${item.id}-${item.name}-${item.value}`] === undefined;
temp[`${item.id}-${item.name}-${item.value}`] = true;
return isUnique;
});
if (items.length !== 0)
result.push(items);
});
console.log(result);

split out object property and values from an array [duplicate]

This question already has answers here:
Remove a JSON attribute [duplicate]
(2 answers)
Closed 7 years ago.
From this json arrays
{
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
}
How to split out some field and turn it intosomething like this
{
"result": [
{
"id": "1",
"type": "B",
},
{
"id": "2",
"type": "A",
}
]
}
I do not want to use splice in my case, above is just sample code.
Try this:
var input = {
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
};
var output = {
result: input.result.map(function(item) {
return {
id: item.id,
type: item.type
};
})
}
Try like this
var json = {
"result": [{
"id": "1",
"name": "John",
"type": "B",
"score": "passed"
}, {
"id": "2",
"name": "Alice",
"type": "A",
"score": "failed"
}
]
};
json.result.forEach(function(item) {
delete item.name;
delete item.score;
});
console.log(json);
iterate over arry and remove age property
var json = [
{"name":"john",
"age":"30",
"gender":"male"},
{"name":"Alice",
"age":"20",
"gender":"female"}
];
json.forEach(function(x){
delete x['age'];
})

Categories

Resources