How to convert array of objects to object with index? - javascript

I have a array like this->
var jsonResponse = [
{
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
{
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
And I want to convert it to ->
{
"abc" : {
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
"ccc": {
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
Probably I dont want foreach.
We can do partial with Object.assign( arrayDetails, ...jsonResponse);
But how to do object index?

let indexedResult = {};
jsonResponse.map(obj => indexedResult[obj.name] = obj)
console.log(JSON.stringify(indexedResult));

Related

Add an Array to an JSON Object

In my API im receiving a JSON with 2 arrays, one Employees and another with Managers, the goal is to add the Managers to each Employee, knowing that the 1st index of the managers corresponds to the 1st index of the employees and so on:
This is an example of the request to the API
{
"employees" : [ {
"code" : "111111",
"name" : "Zé"
},
{
"code" : "222222",
"name" : "João"
},
{
"code" : "444444",
"name" : "António"
}],
"managers" : [
[
{
"name": "vitor",
"level" : "1"
},
{
"name": "Antonio",
"level" : "2"
}
],
[
{
"name": "Jose",
"level" : "1"
},
{
"name": "Ines",
"level" : "2"
}
],
[
{
"name": "Luis",
"level" : "1"
},
{
"name": "Ana",
"level" : "2"
}
]
]
}
and my goal is to get something like this:
[
{
"code": "111111",
"name": "Zé",
"managers": [
{
"name": "vitor",
"level": "1"
},
{
"name": "Antonio",
"level": "2"
}
]
},
{
"code": "222222",
"name": "João",
"managers": [
{
"name": "Jose",
"level": "1"
},
{
"name": "Ines",
"level": "2"
}
]
},
{
"code": "444444",
"name": "António",
"managers": [
{
"name": "Jose",
"level": "1"
},
{
"name": "Ines",
"level": "2"
}
]
}
]
I already tried some things but i can't get the expected result :(
Hope you can help me!! Thanks
function associate_employee_managers({ employees, managers }) {
return employees && employees.length
&& employees
.map((emp, index) => {
return {
...emp,
["managers"]: managers && managers[index] || []
};
}) || {};
}
Considerations
There is 1-1 correspondence(based on index) between entries inside employees array and managers array
Illustration
function associate_employee_managers({
employees,
managers
}) {
return employees && employees.length &&
employees
.map((emp, index) => {
return {
...emp,
["managers"]: managers && managers[index] || []
};
}) || {};
}
const jsonResponse = {
"employees": [{
"code": "111111",
"name": "Zé"
},
{
"code": "222222",
"name": "João"
},
{
"code": "444444",
"name": "António"
}
],
"managers": [
[{
"name": "vitor",
"level": "1"
},
{
"name": "Antonio",
"level": "2"
}
],
[{
"name": "Jose",
"level": "1"
},
{
"name": "Ines",
"level": "2"
}
],
[{
"name": "Luis",
"level": "1"
},
{
"name": "Ana",
"level": "2"
}
]
]
}
console.log(associate_employee_managers(jsonResponse));
WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

How to conditionally sort and right shift a JSON array?

I have a JSON array as follows :
[{
"name": "ABC",
"default": false,
"details": [
{
"detail1": "value1"
},
{
"detail2": "value2"
}
]
},
{
"name": "PQR",
"default": false,
"details": [
{
"detail3": "value3"
},
{
"detail4": "value4"
}
]
},
{
"name": "XYZ",
"default": true,
"details": [
{
"detail5": "value5"
},
{
"detail6": "value6"
}
]
}]
Now if the default value is true , I want it to be the first element of the array and rest of the elements should be sorted alphabetically based on the name . Only one of the element will have default as true or all the elements will have default as false.
The expected JSON after sorting should be :
[{
"name": "XYZ",
"default": true,
"details": [
{
"detail5": "value5"
},
{
"detail6": "value6"
}
]
},
{
"name": "ABC",
"default": false,
"details": [
{
"detail1": "value1"
},
{
"detail2": "value2"
}
]
},
{
"name": "PQR",
"default": false,
"details": [
{
"detail3": "value3"
},
{
"detail4": "value4"
}
]
}]
I have tried this code for sorting the JSON array :
jsonArray.sort( function( a, b ) {
a = a.name.toLowerCase();
b = b.name.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
});
But I am not able to figure out how to check for the default value and sort accordingly. How do I achieve the expected result?
You're on the right way. Just modify the function to include the check for default:
jsonArray.sort( function( a, b ) {
const name1 = a.name.toLowerCase();
const name2 = b.name.toLowerCase();
return (b.default - a.default) || ((name1 > name2) - (name2 > name1))
});
I've got the quick code for string comparison from here: https://stackoverflow.com/a/17765169/2244262

push elements of each object inside each object inside another array

I have two arrays, one is my original one called data which consists of :
const datas = [
{
name: 'core Test',
item: [
{
name: 'test/core/core.js',
item: "item1"
}
]
},
{
name: 'users Test',
item: [
{
name: 'test/users/user.js',
item: "item2"
}
]
}
]
And i have another array called replace, which i'm trying to push each of its elements inside my original one, inside the
const replace = [
{
type: "test1",
number: "1",
},
{
type: "test2",
number: "2",
}
]
Here is my code :
const transformedData = datas.map(data => {
data.item = data.item.map(x => ({
name: x.name,
type: replace.map(y=>{return y;})
}))
return data
})
The output i get :
[
{
"name": "core Test",
"item": [
{
"name": "test/core/core.js",
"type": [
{ "type": "test1", "number": "1" },
{ "type": "test2", "number": "2" }
]
}
]
},
{
"name": "users Test",
"item": [
{
"name": "test/users/user.js",
"type": [
{ "type": "test1", "number": "1" },
{ "type": "test2", "number": "2" }
]
}
]
}
]
The output i want :
[
{
"name": "core Test",
"item": [
{
"name": "test/core/core.js",
"type": { "type": "test1", "number": "1" }
}
]
},
{
"name": "users Test",
"item": [
{
"name": "test/users/user.js",
"type": { "type": "test2", "number": "2" }
}
]
}
]
This is because you're mapping all the way through the replace array every single time for each time you're inside of a value inside of datas. Instead you want to keep track of the index with your original map so then you only have one instance each time.
Try something like:
const transformedData = datas.map((data, index) => {
data.item = data.item.map(x => ({
name: x.name,
type: replace[index]
}))
return data;
});

How to extract value of nested object array?

I'm trying to extract all links IDs of the object array shown below. This is how I was trying to get that:
const linkIDs = array
.filter(d => d.links)
.map(d => d.links)
But this gives me a nested array, which is not what I wanted.
[
{
"id: "1",
"links": [
{
"id" : "Dn59y87PGhkJXpaiZ",
"type" : "article"
},
{
"id" : "PGhkJXDn59y87paiZ",
"type" : "article"
}
]
},
{
"id: "2",
"links": [
{
"id" : "GhkJXpaiZDn59y87P",
"type" : "article"
}
]
},
{
"id": "3"
}
]
So in this example I need the result
[ "Dn59y87PGhkJXpaiZ", "PGhkJXDn59y87paiZ", "GhkJXpaiZDn59y87P" ]
You can do like bellow, without using any other library.
var data = [
{
"id": "1",
"links": [
{
"id" : "Dn59y87PGhkJXpaiZ",
"type" : "article"
},
{
"id" : "PGhkJXDn59y87paiZ",
"type" : "article"
}
]
},
{
"id": "2",
"links": [
{
"id" : "GhkJXpaiZDn59y87P",
"type" : "article"
}
]
},
{
"id": "3"
}
];
var result = data.filter(e => e.links)
.map(e => e.links.map(link => link.id))
.reduce((a, b) => a.concat(b), []);
console.log(result);
I propose a more readable syntax in plain JS:
var data = [
{
"id": "1",
"links": [
{
"id" : "Dn59y87PGhkJXpaiZ",
"type" : "article"
},
{
"id" : "PGhkJXDn59y87paiZ",
"type" : "article"
}
]
},
{
"id": "2",
"links": [
{
"id" : "GhkJXpaiZDn59y87P",
"type" : "article"
}
]
},
{
"id": "3"
}
];
var result = data.filter(e => e.links)
.map(e => e.links)
.flat()
.map(e => e.id)
console.log(result);
You need to produce your array before mapping. Reduce in Js is very useful function ;)
arr = [
{
"id": "1",
"links": [
{
"id" : "Dn59y87PGhkJXpaiZ",
"type" : "article"
},
{
"id" : "PGhkJXDn59y87paiZ",
"type" : "article"
}
]
},
{
"id": "2",
"links": [
{
"id" : "GhkJXpaiZDn59y87P",
"type" : "article"
}
]
},
{
"id": "3"
}
];
var result = arr.filter(a=>a.links).reduce((acc, a) => {
return acc.concat(a.links)
}, []).map(a=>a.id);
console.log(result);
You can use lodash's flatMap() , where each filtered item is transformed using map().
DEMO
var data = [
{
"id": 1,
"links": [
{
"id": "Dn59y87PGhkJXpaiZ",
"type": "article"
},
{
"id": "PGhkJXDn59y87paiZ",
"type": "article"
}
]
},
{
"id": "2",
"links": [
{
"id": "GhkJXpaiZDn59y87P",
"type": "article"
}
]
},
{
"id": "3"
}
];
var result = _.flatMap(data, item =>
_(item.links)
.map(v => (v.id))
.value()
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

Trouble creating query in MongoDB with subquery

I have a dataset that looks something like this:
{
"id": "02741544",
"items": [{
"item": "A"
}]
}, {
"id": "02472691",
"items": [{
"item": "A"
}, {
"item": "B"
}, {
"item": "C"
}]
}, {
"id": "01316523",
"items": [{
"item": "A"
}, {
"item": "B"
}]
}, {
"id": "01316526",
"items": [{
"item": "A"
}, {
"item": "B"
}]
}, {
"id": "01316529",
"items": [{
"item": "A"
}, {
"item": "D"
}]
},
I'm trying to craft a query that will give me an output that looks like this:
{
"item": "A",
"ids": [{
"id": "02741544"
}, {
"id": "02472691"
}, {
"id": "01316523"
}, {
"id": "01316526"
}, {
"id": "01316529"
}]
}, {
"item": "B",
"ids": [{
"id": "02472691"
}, {
"id": "01316523"
}, {
"id": "01316526"
}]
}, {
"item": "C",
"ids": [{
"id": "02472691"
}]
}, {
"item": "D",
"ids": [{
"id": "02472691"
}]
},
Basically, I'm trying to get the distinct items from the item array in the object, and then returning an array of ids for each obj that has that item in it's item array.
Better use the aggregation framework in which you need to run an operation that consists of the following pipeline steps (in the given order):
$unwind - This initial step will flatten the items array i.e. it produces a copy of each document per array entry. This is necessary for processing the documents further down the pipeline as "denormalised" documents which you can aggregate as groups.
$group - This will group the flattened documents by the item subdocument key and create the ids list by using the $push accumulator operator.
-- UPDATE --
As #AminJ pointed out in the comments, if items can have duplicate item values and you don't want duplicate ids in the result you can use $addToSet instead of $push
The following example demonstrates this:
db.collection.aggregate([
{ "$unwind": "$items" },
{
"$group": {
"_id": "$items.item",
"ids": {
"$push": { "id": "$id" } /* or use
"$addToSet": { "id": "$id" } if you don't want duplicate ids */
}
}
}
])
Sample Output
{
"_id" : "A",
"ids" : [
{ "id" : "02741544" },
{ "id" : "02472691" },
{ "id" : "01316523" },
{ "id" : "01316526" },
{ "id" : "01316529" }
]
}
/* 2 */
{
"_id" : "B",
"ids" : [
{ "id" : "02472691" },
{ "id" : "01316523" },
{ "id" : "01316526" }
]
}
/* 3 */
{
"_id" : "C",
"ids" : [
{ "id" : "02472691" }
]
}
/* 4 */
{
"_id" : "D",
"ids" : [
{ "id" : "01316529" }
]
}
The result from an aggregate() function is a cursor to the documents produced by the final stage of the aggregation pipeline operation. So if you want the results in an array you can use the cursor's toArray() method which returns an array that contains all the documents from it.
For example:
var pipeline = [
{ "$unwind": "$items" },
{
"$group": {
"_id": "$items.item",
"ids": {
"$push": { "id": "$id" } /* or use
"$addToSet": { "id": "$id" } if you don't want duplicate ids */
}
}
}
],
results = db.collection.aggregate(pipeline).toArray();
printjson(results);
Here's a solution using an aggregation pipeline:
db.col.aggregate([
{
$unwind: "$items"
},
{
$project: {
id: 1,
item: "$items.item"
}
},
{
$group: {
_id: "$item",
ids: {
$push: "$id"
}
}
}
])

Categories

Resources