How to compare and manipulate json object [closed] - javascript

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.

Related

How can i filter result if i have array in body

i have a payload
{
"category": "Mobile",
"price": {
"from": "10",
"to": "50"
},
"location": [
"Jakrta",
"Bandung",
"Surabaya"
],
"rating": [
"1",
"2",
"3"
]
}
i want to find all object which have rating 1 or 2 or 3 and also have any location
Basically i am creating a filter for an ecommerce store i which we will get multiple location and multiple ratings as well so we will return only those object which have matched property. i am attaching a screenshot of UI for better understanding.
i want to run this filter with multiple location and multiple checked checkbox
You can do create a filter dynamically:
const { category, price, location, rating } = req.body;
const filter = {};
if (category) filter.category = category;
if (price) filter.price = { $gte: parseInt(price.from, 10), $lte: parseInt(price.to, 10) };
if (location?.length) filter.location = { $in: location };
if (rating?.length) filter.rating = { $in: rating };
const data = await Collection.find(filter);
If you want to filter your objects, you should use filter() from your array :
const arr = [{
"category": "Mobile1",
"price": {
"from": "10",
"to": "50"
},
"location": [
"Jakrta",
"Bandung",
"Surabaya"
],
"rating": [
"1",
"2",
"3"
]
},
{
"category": "Mobile2",
"price": {
"from": "10",
"to": "50"
},
"location": [
"Jakrta",
"Bandung",
"Surabaya"
],
"rating": [
"2",
"3"
]
}];
const result = arr.filter(el => el.rating.includes("1") || el.rating.includes("2") || el.rating.includes("3"));
console.log(result);

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.

Iterate array of objects with string array [duplicate]

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);

Returning new arrays using map in javascript [duplicate]

This question already has answers here:
Changing arrays using map in javascript
(7 answers)
Closed 4 years ago.
I am building one nodejs application where in req.body:
I have this object:
{
"id": 8,
"username": "sameer",
"age": "20"
"details": [
{
"category": {
"id": 1,
"nickname": "sam"
}
},
{
"category": {
"id": 2,
"nickname": "basha"
}
}
]
}
My expected output:
{
"id": 8,
"username": "sameer",
"age" : "20",
"final": [1,2] // this id coming from category id.
}
I tried this static way:
var data = 'myJsonStuffs'
var result = data.details.map(x => {
return({
"id": data.id,
"username": data.username,
"age": data.age,
"final": [1,2] // i want this dynamic
});
});
console.log(result);
How to do this using map? is this possible to return dynamic values.
You can use the function map:
Important: this approach will mutate the original obj.
var obj = { "id": 8, "username": "sameer", "age": "20", "details": [ { "category": { "id": 1, "nickname": "sam" } }, { "category": { "id": 2, "nickname": "basha" } } ]};
obj.final = obj.details.map((d) => d.category.id);
delete obj.details
console.log(obj)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Keeping the original obj structure
var obj = { "id": 8, "username": "sameer", "age": "20", "details": [ { "category": { "id": 1, "nickname": "sam" } }, { "category": { "id": 2, "nickname": "basha" } } ]};
var newObj = Object.assign({}, {
id: obj.id,
username: obj.username,
age: obj.age,
final: obj.details.map((d) => d.category.id)
});
console.log(newObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is how I'd do it.
I hope this helps
const data = {
id: 8,
username: "sameer",
age: "20",
details: [
{
category: {
id: 1,
nickname: "sam"
}
},
{
category: {
id: 2,
nickname: "basha"
}
}
]
};
const result = Object.assign(
{}, // Empty object to avoid mutating 'data'
data,
{ details: data.details.map(detail => detail.category.id) } // Override 'details'
);
console.log(result);
Maybe you want this?
you can use 'i' as index and populate arrays with that
var data = 'myJsonStuffs'
var result = data.details.map((x,i) => {
return({
"id": data.id,
"username": data.username,
"age": data.age,
"final": [i] // i want this dynamic
});
});
console.log(result);

Object.assign nested array with only certain properties

I have json data from below. The goal is to take all the Orders and combine them into one array while maintaining the Amount and the IdNumber so that I can use lodash _.groupBy on the Type.
In the end I'll have, for example, Type: test with each IdNumber and the Order Amounts that correspond to that IdNumber
I tried Object.assign on the data and did
data.forEach(d => {
let orders = d['Orders'];
let newOrders = Object.assign({}, {Idnumber: data.IdNumber, Orders: orders});
let groupedOrders = _.groupBy(newOrders, 'Type');
});
But, I'm not sure how to get just the Amount and Type of orders and merge them into one array. I'm also unclear if Object.assign is keeping track of the IdNumber with the Orders. when going through the array. I've never used Object.assign so perhaps that isn't even the right method to go about what I need.
Json data:
data = [
{
"Name": "abc",
"Amount": 3000,
"Idnumber": "001",
"Date": "11/17/2017",
"Orders": [
{
"Order Number": "11",
"Date": "11/18/2017",
"Amount": 1000,
"Type": "test"
},
{
"Order Number": "12",
"Date": "12/31/2017",
"Amount": 2000,
"Type": "trial"
}
],
"foo": "foo",
"foo2": foo,
"foo3": "foo",
"foo4": "foo"
},
{
"Name": "def",
"Amount": 5000,
"Idnumber": "002",
"Date": "12/15/2017",
"Orders": [
{
"Order Number": "10",
"Date": "11/02/2017",
"Amount": 7600,
"Type": "trial"
},
{
"Order Number": "16",
"Date": "05/31/2018",
"Amount": 15000,
"Type": "interim"
}
],
"foo": "foo",
"foo2": foo,
"foo3": "foo",
"foo4": "foo"
}
]
You can use array#reduce and array#map to inject Idnumber to each order and later on use array#reduce to group data based on the Type.
const data = [{"Name":"abc","Amount":3000,"Idnumber":"001","Date":"11/17/2017","Orders":[{"Order Number":"11","Date":"11/18/2017","Amount":1000,"Type":"test"},{"Order Number":"12","Date":"12/31/2017","Amount":2000,"Type":"trial"}],"foo":"foo","foo2":"foo","foo3":"foo","foo4":"foo"},{"Name":"def","Amount":5000,"Idnumber":"002","Date":"12/15/2017","Orders":[{"Order Number":"10","Date":"11/02/2017","Amount":7600,"Type":"trial"},{"Order Number":"16","Date":"05/31/2018","Amount":15000,"Type":"interim"}],"foo":"foo","foo2":"foo","foo3":"foo","foo4":"foo"}];
var result = data.reduce((r, {Orders, Idnumber}) => {
let orders = Orders.map(order => Object.assign({}, order, {Idnumber}));
return r.concat(orders);
},[]);
console.log(result);
console.log('--------------Grouped By----------');
var groupedBy = result.reduce((r,o) => {
r[o.Type] = r[o.Type] || [];
r[o.Type].push(o)
return r;
},{});
console.log(groupedBy);
.as-console-wrapper { max-height: 100% !important; top: 0; }
newOrder = data.map(d => ({Orders: d.Orders, idNumber: d.Idnumber}))

Categories

Resources