Creating dynamic json from already existing json - javascript

I am getting one json in this structure:
{
data: {
ads: [
{
name: "0",
id: "81"
},
{
name: "0",
id: "82"
}
]
}
}
i want to create one more json from the existing one like this.
{
json{
81:[
{
name: "a",
id: "81"
},
]
82:[
{
name: "c",
id: "82"
}
]
}
}
I am not getting how to create according to the id. Can anyone help me in this. using javascript i am want to create this

You can use bracket notation to achieve this:
var obj = {
data: {
ads: [
{
name: "0",
id: "81"
},
{
name: "0",
id: "82"
}
]
}
};
var newobj = {
json: {}
};
for(var i in obj.data.ads) {
var a = obj.data.ads[i];
if(!(a.id in newobj.json)) {
newobj.json[a.id] = [];
}
newobj.json[a.id].push({ name: a.name, id: a.id });
}
Here is a fiddle to demonstrate.

Related

Need to return existing data structure with update objects

I wanted to update the object when it pass the check but getting different result then expected.
What is preferred way to get the expected?
This the sample data:
var abc = [
{
type: "manager",
members: [{name: 'bob'}, {name: 'rob'}]
},
{
type: "clerk",
members: [{name: 'foo'}, {name: 'bar'}]
}
];
Using this function :
function funn() {
return abc.map((cate) => {
return cate.members.map((mem) => {
if (mem.name === 'bob') {
mem['isBob'] = true;
}
return mem;
});
});
}
I wanted in this format (expected):
[
{
type: 'manager',
members: [{ name: 'bob', isBob: true }, { name: 'rob' }],
},
{
type: 'clerk',
members: [{ name: 'foo' }, { name: 'bar' }],
},
];
The actual is like this:
[
{
members: [{ name: 'bob' }, { name: 'rob' }],
},
{
members: [{ name: 'foo' }, { name: 'bar' }],
},
];
You just need to find the element in the members array and if it is present then add the isBob property.
var abc = [{
type: "manager",
members: [{
name: "bob"
}, {
name: "rob"
}],
},
{
type: "clerk",
members: [{
name: "foo"
}, {
name: "bar"
}],
},
];
const result = abc.map((obj) => {
const isExist = obj.members.find((o) => o.name === "bob");
if (isExist) isExist.isBob = true;
return obj;
});
console.log(result);
The output you showed for your code is not matching when i run it.
Here I have modified your code a bit:
Instead of returning an array from the outer .map(), I am returning an object which has a type and members category.
function funn() {
return abc.map((cate) => {
let cateMembers = cate.members.map((mem) => {
if (mem.name === 'bob') {
mem['isBob'] = true;
}
return mem;
});
return { type : cate.type , members : cateMembers};
});
}
Remember to check like this : console.log(funn())
You could do something like this:
var abc = [
{
type: "manager",
members: [{name: 'bob'}, {name: 'rob'}]
},
{
type: "clerk",
members: [{name: 'foo'}, {name: 'bar'}]
}
];
function funn() {
abc.forEach(el => {
el.members.forEach(el2 => {
if(el2.name === 'bob') el2.isBob = true
})
})
return abc
}
console.log(funn())

Creating an array from 2 other arrays

I have two arrays of objects as shown below :
categories = [
{ name: "performance", id: 1 },
{ name: "understanding", id: 2 }
]
queries = [
{ name: "A", categoryId: "1" },
{ name: "B", categoryId: "1" },
{ name: "C", categoryId: "1" },
{ name: "D", categoryId: "2" }
]
Now, using these two arrays of objects, I need following array as a result:
process = [
{ category: "performance", query: [
{ name: "A" },
{ name: "B" },
{ name: "C" }
]},
{ category: "understanding", query: [{ name: "D" }] }
]
I have to match the categoryId with process's id and then create the above array.
I have tried the following way to solve this but could not get desired result.
const test = [];
categories.forEach((element) => {
const r = que.filter((res) => res.categoryId === element.id);
queries.forEach((rt) => {
if (rt.categoryId === element.id) {
test.push({
category: element.name,
query: [{
name: rt.name,
}],
});
}
});
});
Is this possible using any built in array methods in JavaScript?
Thanks in advance
Using Array.reduce, you can group queries by categoryId.
Based on that groupedBy object, using Array.map, you can get the result you want.
const categories = [{
name: "performance",
id: "1"
},{
name: "understanding",
id: "2"
}];
const queries = [{
name: "A",
categoryId: "1"
}, {
name: "B",
categoryId: "1"
}, {
name: "C",
categoryId: "1"
}, {
name: "D",
categoryId: "2"
}];
const groupByQueries = queries.reduce((acc, cur) => {
acc[cur.categoryId] ?
acc[cur.categoryId].push({ name: cur.name })
: acc[cur.categoryId] = [ { name: cur.name } ];
return acc;
}, {});
const result = categories.map(({ name, id }) => ({
category: name,
query: groupByQueries[id]
}));
console.log(result);
categories = [{name: "performance", id: 1},{name: "understanding", id: 2}];
queries = [{name: "A", categoryId: "1"}, {name: "B", categoryId: "1"}, {name: "C", categoryId: "1"}, {name: "D", categoryId: "2"}]
const test = [];
categories.forEach((element) => {
let temp = []
queries.map(item =>{
if(element.id.toString() === item.categoryId)
temp.push({name: item.name})
})
test.push({category:element.name,query:temp})
});
console.log(test)

use filter of Lodash/Javascript to get the filtered data

I have two array of objects.
const firstObj = [
{ Id: "1", Name: "Peter" },
{ Id: "2", Name: "John" },
{ Id: "12", Name: "jessy" },
];
const secondObj = [
{ Id: "1", Name: "Roa", original: { Id: "1" } },
{ Id: "2", Name: "John2", original: { Id: "2" } },
{ Id: "5", Name: "Rachel", original: { Id: "3" } },
];
Here, I am trying to filter data on the basis of Id and return the filtered firstObj
So, here firstObj has an entry { Id: "12", Name: "jessy" } this object whose Id does not match with the secondObj.original.Id so, firstObj will have the given result.
what I tried was
firstObj.filter(
firstObj,
secondObj.map((second) => {
return firstObj.Id === second.original.Id;
}),
);
But this does not work. Can any one help me out here , using Lodash or Js filter.
output would be -> [{"Id": "3", "Name": "jessy"}]
Is this what you are looking for?
const firstObj = [
{ Id: "1", Name: "Peter" },
{ Id: "2", Name: "John" },
{ Id: "12", Name: "jessy" },
];
const secondObj = [
{ Id: "1", Name: "Roa", original: { Id: "1" } },
{ Id: "2", Name: "John2", original: { Id: "2" } },
{ Id: "1", Name: "Rachel", original: { Id: "3" } },
];
const result = lodash.filter(firstObj, (firstItem) => {
return !lodash.some(secondObj, (secondItem) => {
return firstItem.Id === secondItem.original.Id;
});
});
Live: https://stackblitz.com/edit/js-addy5t?file=index.js
why use loadash for this. you can use native filter and find functions to achieve this
const filter = firstObj.filter(item => {
return secondObj.find(itm => itm.original.id === item.id)
});
You could use native method of Array.filter() and Array.some() to achieve the desired output.
Please check below working code snippet
ES6
const firstObj = [
{ Id: "1", Name: "Peter" },
{ Id: "2", Name: "John" },
{ Id: "12", Name: "jessy" },
],
secondObj = [
{ Id: "1", Name: "Roa", original: { Id: "1" } },
{ Id: "2", Name: "John2", original: { Id: "2" } },
{ Id: "1", Name: "Rachel", original: { Id: "3" } },
];
let result = firstObj.filter(({Id})=> !secondObj.some(item => item.original.Id === Id));
console.log(result)

Javascript Alphabetised Object Key Sorting

I'm wondering, I have the following data structure:
data = [
{
name: 'Alpha',
},
{
name: 'Alfa',
},
{
name: 'Bravo',
},
{
name: 'Brafo',
},
{
name: 'Charlie',
},
{
name: 'Charly',
},
...
{
name: 'Zulu',
},
{
name: 'Zulo',
},
]
I'm expecting there to be at least one, usually more, key for each letter of the alphabet. However, if there isn't a single data.name I would still like in the below data structure to have an empty domains array [].
I was wondering, how could this be manipulated into the following data structure:
data = {
a: {
domains: [
{
name: 'Alpha',
},
{
name: 'Alfa',
},
],
},
b: {
domains: [
...
]
},
...
z: {
domains: [
...
]
},
};
I have used a few methods, which involved a pre-constructed "alphbetised" key = object array, then filtered each on the first letter of the data.name value...but I was wondering if there was a standard and performant method to acheive this?
Using reduce()
const data = [{name:"Alpha"},{name:"Alfa"},{name:"Bravo"},{name:"Brafo"},{name:"Charlie"},{name:"Charly"},{name:"Zulu"},{name:"Zulo"}]
const res = data.reduce((a, v) => {
// prepare key
let key = v.name.substring(0,1).toLowerCase()
// check key in accumulator
if (!a[key]) {
// assign domain object
a[key] = {domains: []}
}
// push domain array
a[key].domains.push(v)
return a
}, {})
console.log(res)
Here is what you want:
data = [
{
name: 'Alpha',
},
{
name: 'Alfa',
},
{
name: 'Bravo',
},
{
name: 'Brafo',
},
{
name: 'Charlie',
},
{
name: 'Charly',
},
{
name: 'Zulu',
},
{
name: 'Zulo',
},
];
console.log(data.reduce((a, c) => {
const firstLetter = c.name[0].toLowerCase();
if (a[firstLetter]) {
a[firstLetter].domains.push(c);
} else {
a[firstLetter] = { domains: [c] };
}
return a;
}, {}));

Flatten an object of child arrays

I have Object which look like
list:{
dynamicPerson: [
0: {
name:"Andrew",
company:"xCompany"
},
1: {
name:"Joseph",
company:"zCompany"
}
]
dynamicPerson2: [
0: {
name:"Andrew",
company:"xCompany"
},
1: {
name:"Joseph",
company:"zCompany"
}
]
}
I want it like
List:[
0: {
name:"Andrew",
company:"xCompany"
},
1: {
name:"Joseph",
company:"zCompany"
},
2: {
name:"Andrew",
company:"xCompany"
},
3: {
name:"Joseph",
company:"zCompany"
}
]
Note DynamicPerson is run time generated key.
You can iterate trought the keys of the object. Map the arrays to an array of array and then flatten it.
let flattened = Object.keys(list).map(key => list[key]).flat();
I modified your input slightly, because it was not syntactically right.
let list = {
dynamicPerson: [
{
name: "Andrew",
company: "xCompany"
},
{
name: "Joseph",
company: "zCompany"
}
],
dynamicPerson2: [
{
name: "Andrew",
company: "xCompany"
},
{
name: "Joseph",
company: "zCompany"
}
]
};
let flattened = Object.keys(list)
.map(key => list[key])
.flat();
console.log(flattened);
You'll find it yourself by looking for: convert object to array-of-key-value-pairs
But maybe look at the snipped in here: how-to-convert-an-object-to-an-array-of-key-value-pairs can help you
You can use flatMap():
Object.values(list).flatMap(s => s);
An example:
let list ={
dynamicPerson: [
{
name:"Andrew",
company:"xCompany"
},
{
name:"Joseph",
company:"zCompany"
}
]
, dynamicPerson2: [
{
name:"Andrew",
company:"xCompany"
},
{
name:"Joseph",
company:"zCompany"
}
]
}
const result = Object.values(list).flatMap(s => s);
console.log(result);
You can also use Object.values() and flat:
let list = {
dynamicPerson: [{
name: "Andrew",
company: "xCompany"
},
{
name: "Joseph",
company: "zCompany"
}
],
dynamicPerson2: [{
name: "Andrew",
company: "xCompany"
},
{
name: "Joseph",
company: "zCompany"
}
]
}
let List = Object.values(list).flat();
console.log(List);

Categories