Modify array to stop object from being nested - javascript

I have an example array
const array = [
{ obj: [{ fields: { title: 'titleValue1' } }, { fields: { title: 'titleValue2' } }] },
{ obj: [{ fields: { title: 'titleValue3' } }, { fields: { title: 'titleValue4' } }] },
]
I'm looking to modify the array to:
const modifiedArray = [
{ obj: [{ title: 'titleValue1' }, { title: 'titleValue2' }] },
{ obj: [{ title: 'titleValue3' }, { title: 'titleValue4' }] },
]
So when I loop over the modified array I can call 'obj.title' instead of 'obj.fields.title'
I think this can be achieved using .map. So far I have tried:
const ammendedArray = array.map(item => ({ ...item, title: item.map(e => e.fields) }))
But returning 'item.map is not a function'
Any help with this would be much appreciated.

In your code you are trying to use map for an item in the top level array. Which is like this for the first item,
{ obj: [{ fields: { title: 'titleValue1' } }, { fields: { title: 'titleValue2' } }] }
As you can see item is an object. You can not map through an object. What you can do is map through item.obj
const ammendedArray = array.map(item => ({ ...item, title: item.obj.map(e => e.fields) }))
But it will not solve your problem you will get a wrong array of objects like this,
[
{
obj: [{ fields: { title: 'titleValue1' } }, { fields: { title: 'titleValue2' } }],
title: [{ title: 'titleValue1' }, { title: 'titleValue2' }]
},
...
]
You will have to update the obj key instead. What you need to do is the following,
const array = [
{ obj: [{ fields: { title: 'titleValue1' } }, { fields: { title: 'titleValue2' } }] },
{ obj: [{ fields: { title: 'titleValue3' } }, { fields: { title: 'titleValue4' } }] },
]
const res = array.map((item) => {
return {
obj: item.obj.map(i => {
return i.fields
})
};
});
console.log(res);

I could reach to that like this :)
const array = [
{ obj: [{ fields: { title: 'titleValue1' } }, { fields: { title: 'titleValue2' } }] },
{ obj: [{ fields: { title: 'titleValue3' } }, { fields: { title: 'titleValue4' } }] },
]
// pass a function to map
const map1 = array.map((x)=>{
const filedsArray = [...x.obj]
x.obj = []
filedsArray.forEach((y)=>{
x.obj.push({title:y.fields.title})
})
return x
})
console.log(map1);

Related

using map method the new object is not inserting

I am trying to add a new object using the map, but the new object is not inserted, i think there is an issue with my logic,
What I am trying to is I have some results data, I am trying to structure it, the English 1st part will be an object and English 2nd part will be another object, these 2 objects will be inside children, like the example
[
{
title: "English",
children: [
0:{
title: "1ST",
children: [
{
title: "CQ",
dataIndex: "CQ",
},
{
title: "MCQ",
dataIndex: "MCQ",
},
],
},
1:{
title: "2ND",
children: [
{
title: "CQ",
dataIndex: "CQ",
},
{
title: "MCQ",
dataIndex: "MCQ",
},
],
}
]
Here is my code, the English 2nd part is not inserting
const results = [
{ Field: "english_1st_CQ" },
{ Field: "english_1st_MCQ" },
{ Field: "english_2nd_CQ" },
{ Field: "english_2nd_MCQ" },
];
const structureData = (results) => {
let arr = [];
results.map((value) => {
if (value.Field.includes("_")) {
const [subjectName, subjectPart, suffix] = value.Field.split("_");
const isSubjectExist = arr.find((el) => el.title == subjectName);
if (isSubjectExist !== undefined) {
isSubjectExist.children.map((element, i) => {
if (element.title == subjectPart) {
element = {
title: subjectPart,
children: [
{
title: suffix,
dataIndex: suffix,
},
],
};
} else {
element.children["2"] = {
title: suffix,
dataIndex: suffix,
};
}
});
} else {
const subject = {
title: subjectName,
children: [
{
title: subjectPart,
children: [
{
title: suffix,
dataIndex: suffix,
},
],
},
],
};
arr.push(subject);
}
}
});
return arr;
};
console.log(structureData(results));
The issue is here:
if (element.title == subjectPart) {
element = {
title: subjectPart,
children: [
{
title: suffix,
dataIndex: suffix,
},
],
};
I think that using a functional approach helps to better keep track of and reason about what is happening during the iterations because it keeps things DRY:
function resolveNode (arr, title) {
const node = arr.find(node => node.title === title) ?? {title, children: []};
if (!arr.includes(node)) arr.push(node);
return node;
}
function parse (input) {
const result = [];
for (const {Field} of input) {
const [subject, part, suffix] = Field.split('_');
const s = resolveNode(result, subject);
const p = resolveNode(s.children, part);
// Don't create duplicates:
if (!p.children.find(node => node.title === suffix)) {
p.children.push({title: suffix, dataIndex: suffix});
}
}
return result;
}
const input = [
{ Field: "english_1st_CQ" },
{ Field: "english_1st_MCQ" },
{ Field: "english_2nd_CQ" },
{ Field: "english_2nd_MCQ" },
];
const result = parse(input);
const formattedJson = JSON.stringify(result, null, 2);
console.log(formattedJson);

How to delete objects inside an object using an array? (React.js Reducer )

Example of the data (useContext)
data: {
projects:{
'project-1':{
name: 'project-1',
columnIds:['column-1', 'column-2'],
},
'project-2':{
name: 'project-2',
columnIds:['column-3'],
},
},
columns:{
'column-1':{
title: 'column-1',
content: 'abc',
},
'column-2':{
title: 'column-2',
content: 'def',
},
'column-3':{
title: 'column-3',
content: 'ghi',
},
},
}
If I delete the project-1 which has column-1 and column-2, it should also be deleted inside the columns object. So the result should be:
data: {
projects:{
'project-2':{
name: 'project-2',
columnIds:['column-3'],
},
},
columns:{
'column-3':{
title: 'column-3',
content: 'ghi',
},
},
}
I already know how to remove project-1 object but I'm stuck in removing the column-1 and column-2.
This was my code for removing column-1 and `column-2 data:
let newColumn = data.projects[projectname].columnIds.map((item) =>
Object.keys(data.columns).filter((key) => key !== item)
);
You just need to check if there are corresponding column IDs before you delete the property. If there are, iterate over the IDs and delete the columns:
const data = {
projects: {
'project-1': {
name: 'project-1',
columnIds: ['column-1', 'column-2'],
},
'project-2': {
name: 'project-2',
columnIds: ['column-3'],
},
},
columns: {
'column-1': {
title: 'column-1',
content: 'abc',
},
'column-2': {
title: 'column-2',
content: 'def',
},
'column-3': {
title: 'column-3',
content: 'ghi',
},
},
}
const key = 'project-1'
const { columnIds } = data.projects[key]
if (columnIds.length > 0) {
columnIds.forEach(id => {
delete data.columns[id]
})
}
delete data.projects[key]
console.log(data)
You can also create a copy of the object so you don't mutate the original one:
const data = {
projects: {
'project-1': {
name: 'project-1',
columnIds: ['column-1', 'column-2'],
},
'project-2': {
name: 'project-2',
columnIds: ['column-3'],
},
},
columns: {
'column-1': {
title: 'column-1',
content: 'abc',
},
'column-2': {
title: 'column-2',
content: 'def',
},
'column-3': {
title: 'column-3',
content: 'ghi',
},
},
}
function deleteColumns(obj, key) {
const copy = {
projects: { ...obj.projects },
columns: { ...obj.columns }
}
const { columnIds } = copy.projects[key]
if (columnIds.length > 0) {
columnIds.forEach(id => delete copy.columns[id])
}
delete copy.projects[key]
return copy
}
const afterDelete = deleteColumns(data, 'project-1')
console.log(afterDelete)
console.log(data)

pushing an object into an array of objects

i want to push my retrieved results which is an inline string result to my array object item
Here is my code :
arrayObject.push({ type: "type", item: itemArray });
arrayObject.forEach((elementItem) => {
global.forEach((element) => {
const { items } = element;
for (const item in items) {
const title = items[item].title;
elementItem.item.push({ title });
}
});
});
And here is my json file that i retrieve from global, items and title
global: [
{
items: {
xxx: {
title: 'result1',
}
},
}
]
The result i want is like this :
[ { type: 'xxx', item: [ {name: result1 } ] } ]
Here i've used reduce and object.values to produce your expected outcome.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
const global = [{
way: 'type1',
items: {
get: {
title: 'result1',
},
post: {
title: 'result2',
},
put: {
title: 'result3',
},
},
},
{
way: 'type2',
items: {
get: {
title: 'test1',
},
post: {
title: 'test2',
},
put: {
title: 'test3',
},
},
},
]
function mapJsonToTypes(arr) {
const typeAndTitles = (acc, {items, way: type}) => {
return [...acc, {type, item: getTitlesFromItems(items)}]
}
return arr.reduce(typeAndTitles, []);
}
function getTitlesFromItems(items = {}) {
return Object.values(items).map(({ title }) => title)
}
console.log(mapJsonToTypes(global));

Javascript filtering nested arrays

I'm trying to filter a on a nested array inside an array of objects in an Angular app. Here's a snippet of the component code -
var teams = [
{ name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] },
{ name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] },
{ name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }
];
What I'm trying to achieve is if I search for m5 for example my result should be -
var teams = [
{ name: 'Team1', members: [] },
{ name: 'Team2', members: [{ name: 'm5' }] },
{ name: 'Team3', members: [] }
];
So I've got teams and filteredTeams properties and in my search function I'm doing -
onSearchChange(event: any): void {
let value = event.target.value;
this.filteredTeams = this.teams.map(t => {
t.members = t.members.filter(d => d.name.toLowerCase().includes(value));
return t;
})
}
Now this does work to some extent however because I'm replacing the members it's destroying the array on each call (if that makes sense). I understand why this is happening but my question is what would be the best way to achieve this filter?
you were very close, the only thing that you did wrong was mutating the source objects in teams
basically you can use spread operator to generate a new entry and then return a whole new array with new values.
const teams = [
{ name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] },
{ name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] },
{ name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }
];
const value = 'm5';
const result = teams.map(t => {
const members = t.members.filter(d => d.name.toLowerCase().includes(value));
return { ...t, members };
})
console.log(result)
Check this. Instead of hard coded m5 pass your value.
const teams = [
{ name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] },
{ name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] },
{ name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }
];
const filteredTeams = teams.map(team => ({ name: team.name, members: team.members.filter(member => member.name.includes('m5')) }));
console.log(filteredTeams);
You are mutating the original objects, but you could assing new properties to the result object for mapping instead.
var teams = [{ name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] }, { name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] }, { name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }],
result = teams.map(o => Object.assign(
{},
o,
{ members: o.members.filter(({ name }) => name === 'm5') }
));
console.log(result);
console.log(teams);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try to seperate your filter function first:
const filterTeamMembers = (teams, filterArr) => {
const useFilter = filterArr.map(x => x.toLowerCase());
return teams.map(team => ({
...team,
members: team.members.filter(member => useFilter.includes(member.name))
}))
};
// =========== And then:
onSearchChange(event: any): void {
let value = event.target.value;
this.filteredTeams = filterTeamMembers(this.teams, [value]);
}

Setting array keys dynamically based on length

Given an array in this format:
[
[{
name: "name",
value: "My-name"
},
{
name: "qty",
value: "1"
},
{
name: "url",
value: "test.com"
},
{
name: "comment",
value: "my-comment"
}
],
[{
name: "name",
value: "My-name2"
},
{
name: "qty",
value: "3"
},
{
name: "url",
value: "test2.com"
}
],
[{
name: "name",
value: "My-name3"
},
{
name: "qty",
value: "1"
},
{
name: "url",
value: "test3.com"
},
{
name: "comment",
value: "my-comment3"
}
]
]
I'm looking to switch that to:
[
[
{ name: "My-name" },
{ qty: "1" },
{ url: "test.com" },
{ comment: "my-comment", }
],[
{ name: "My-name2" },
{ qty: "3" },
{ url: "test2.com",
],[
{ name: "My-name3", },
{ qty: "1", },
{ url: "test3.com", },
{ comment: "my-comment3", }
]
]
In other words, swapping out the array keys but maintaining the object structure within each array element.
I've tried looping over each element and can swap the keys out using something like:
newArray[iCount][item.name] = item.value;
However I'm then struggling to preserve the object order. Note that the comment field may or may not appear in the object.
With Array.map() function:
var arr = [
[{name:"name",value:"My-name"},{name:"qty",value:"1"},{name:"url",value:"test.com"},{name:"comment",value:"my-comment"}],
[{name:"name",value:"My-name2"},{name:"qty",value:"3"},{name:"url",value:"test2.com"}],
[{name:"name",value:"My-name3"},{name:"qty",value:"1"},{name:"url",value:"test3.com"},{name:"comment",value:"my-comment3"}]
],
result = arr.map(function(a){
return a.map(function(obj){
var o = {};
o[obj.name] = obj.value
return o;
});
});
console.log(result);
Check my moreBetterOutput value. I think will be better.
If you still need a result like your example in the question then you can check output value.
const input = [
[
{
name:"name",
value:"My-name"
},
{
name:"qty",
value:"1"
},
{
name:"url",
value:"test.com"
},
{
name:"comment",
value:"my-comment"
}
],
[
{
name:"name",
value:"My-name2"
},
{
name:"qty",
value:"3"
},
{
name:"url",
value:"test2.com"
}
],
[
{
name:"name",
value:"My-name3"
},
{
name:"qty",
value:"1"
},
{
name:"url",
value:"test3.com"
},
{
name:"comment",
value:"my-comment3"
}
]
]
const output = input.map(arr => arr.map(obj => ({[obj.name]: obj.value})))
const moreBetterOutput = output.map(arr => arr.reduce((acc, item, index) => {
acc[Object.keys(item)[0]] = item[Object.keys(item)[0]];
return acc;
}, {}) )
//console.log(output);
console.log(moreBetterOutput);
Another map function:
const result = array.map( subarray =>
Object.assign(...subarray.map( ({name, value}) => ({ [name] : value }) ))
);

Categories

Resources