push line strings to array of object - javascript

i want to push the data retreived into an array but it only push into the first object.
const arr = [{ name: 'name1', item: [] }, { name: 'name2', item: [] }];
routes.forEach((elementRoute) => {
const { methods } = elementRoute;
for (const m in methods) {
let { title } = methods[m];
arr[0].item.push({
name: title,
request: { method: m,},
});
}
});
my routes array is like this :
[
{
methods: {
get: {
title: 'get users',
},
},
}
];
It only push into the first object of the item array.This is the result i actually want to get :
[
{
"name": "name1",
"item": [
{ "name": "get users", "request": { "method": "get" } } }
]
},
{
"name": "name2",
"item": [
{ "name": "get users", "request": { "method": "get" } } }
]
}
]

You need to iterate arr as well for getting all items filled.
const
arr = [{ name: 'name1', item: [] }, { name: 'name2', item: [] }],
routes = [{ methods: { get: { title: 'get users' } } }, { methods: { get: { title: 'get user id' }, delete: {} } }, ];
arr.forEach(({ item }) =>
routes.forEach(({ methods }) => {
for (const method in methods) {
let { title: name = 'Not specified' } = methods[method];
item.push({ name, request: { method } });
}
})
);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

how to find all matching values based on search input of objects for the nested array of objects

I am looking for a suggestion and fix in my function.
I have a function to find all possible matches for an array of objects having a nested array of objects.
I have tried adding the filter function but it is only giving me matched keywords for the first level and it is getting stopped after that.
Is there anyways I can search for multiple levels?
I have tried the following.
const data = [
{
name: "testmapping",
items: [
{
name: "lv2test1mapping",
items: [
{ name: "lv3test1mapping" },
{ name: "lv3test2mapping" },
{ name: "lv3test3mapping" }
]
},
{
name: "lv2test2mapping"
},
{
name: "lv2test3mapping"
}
]
},
{
name: "test2mapping",
items: [
{
name: "lv2test21mapping",
items: [
{ name: "lv3test21mapping" },
{ name: "lv3test22mapping" },
{ name: "lv3test23mapping" }
]
},
{
name: "lv2test22mapping"
},
{
name: "lv2test23mapping"
}
]
}
];
function getvalue(searchText) {
return data.filter(item => {
return Object.keys(item).some(key => {
return String(item[key])
.toLowerCase()
.includes(searchText.toLowerCase());
});
});
}
console.log("one level", getvalue("test"));
//output
[
{
"name":"testmapping",
"items":[
{
"name":"lv2test1mapping",
"items":[
{
"name":"lv3test1mapping"
},
{
"name":"lv3test2mapping"
},
{
"name":"lv3test3mapping"
}
]
},
{
"name":"lv2test2mapping"
},
{
"name":"lv2test3mapping"
}
]
},
{
"name":"test2mapping",
"items":[
{
"name":"lv2test21mapping",
"items":[
{
"name":"lv3test21mapping"
},
{
"name":"lv3test22mapping"
},
{
"name":"lv3test23mapping"
}
]
},
{
"name":"lv2test22mapping"
},
{
"name":"lv2test23mapping"
}
]
}
]
console.log("second level", getvalue("lv2"));
//expected output
[
{
"name":"lv2test1mapping",
"items":[
{
"name":"lv3test1mapping"
},
{
"name":"lv3test2mapping"
},
{
"name":"lv3test3mapping"
}
]
},
{
"name":"lv2test2mapping"
},
{
"name":"lv2test3mapping"
},
{
"name":"lv2test21mapping",
"items":[
{
"name":"lv3test21mapping"
},
{
"name":"lv3test22mapping"
},
{
"name":"lv3test23mapping"
}
]
},
{
"name":"lv2test22mapping"
},
{
"name":"lv2test23mapping"
}
]
console.log("third level", getvalue("lv3"));
//expected output
[
{
"name":"lv3test1mapping"
},
{
"name":"lv3test2mapping"
},
{
"name":"lv3test3mapping"
},
{
"name":"lv3test21mapping"
},
{
"name":"lv3test22mapping"
},
{
"name":"lv3test23mapping"
}
]
https://stackblitz.com/edit/js-ydnhcg?file=index.js
const data = [
{
name: "testmapping",
items: [
{
name: "lv2test1mapping",
items: [
{ name: "lv3test1mapping" },
{ name: "lv3test2mapping" },
{ name: "lv3test3mapping" }
]
},
{
name: "lv2test2mapping"
},
{
name: "lv2test3mapping"
}
]
},
{
name: "test2mapping",
items: [
{
name: "lv2test21mapping",
items: [
{ name: "lv3test21mapping" },
{ name: "lv3test22mapping" },
{ name: "lv3test23mapping" }
]
},
{
name: "lv2test22mapping"
},
{
name: "lv2test23mapping"
}
]
}
];
function getValue(searchText) {
const localData = [...data];
function getValueLogic(data, searchText) {
const arr = [];
if (data && Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const ele = data[i];
ele && ele.name.includes(searchText)
? arr.push(ele)
: arr.push(...getValueLogic(ele.items, searchText));
}
}
return arr;
}
return getValueLogic(localData, searchText);
}
console.log("one level", getValue("test"));
console.log("second level", getValue("lv2"));
console.log("third level", getValue("lv3"));
console.log("Actual Data", data);
Recursion is the key! The below function should meet your requirement.
const data = [...] //your data
function getValue(searchText) {
const localData = [...data];
function getValueLogic(data, searchText) {
const arr = [];
if (data && Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const ele = data[i];
ele && ele.name.includes(searchText)
? arr.push(ele)
: arr.push(...getValueLogic(ele.items, searchText));
}
}
return arr;
}
return getValueLogic(localData, searchText);
}
console.log("one level", getValue("test"));
console.log("second level", getValue("lv2"));
console.log("third level", getValue("lv3"));
console.log("Actual Data", data);

Modify array to stop object from being nested

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

I have to map a composed array

I have an array I need to get all the tasks that have the same record Id in an array
workspaces=[{recordId:1,tasks:[{title:'me'},{title:'we'}]},{recordId:2,tasks:[{title:'hi'},{title:'it'}]},{recordId:1,tasks:[{title:'they',{title:'she'}]}]
the final result will be like:[[recordId:1,tasks:[{title:'me'},{title:'we'},{title:'they',{title:'she'}]],[recordId:2,tasks:[{title:'hi'},{title:'it'}]]]
i used groupBy from lodash but i did get a separate arrays anyone have any idea how to implement that.
A possible solution could be a two step approach by
collecting items for a certain group
render the array in the wanted format.
This approach features a Map and uses Array.from for getting the wanted result.
var workspaces = [{ recordId: 1, tasks: [{ title: 'me' }, { title: 'we' }] }, { recordId: 2, tasks: [{ title: 'hi' }, { title: 'it' }] }, { recordId: 1, tasks: [{ title: 'they' }, { title: 'she' }] }],
grouped = Array.from(
workspaces.reduce((m, { recordId, tasks }) =>
m.set(recordId, [...(m.get(recordId) || []), ...tasks]), new Map),
([recordId, tasks]) => ({ recordId, tasks })
);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz solution is more sophisticated, but harder to read.
You can achieve the same like this:
const workspaces= [
{recordId: 1, tasks: [{title:'me'}, {title:'we'}] },
{recordId: 2, tasks: [{title:'hi'}, {title:'it'}] },
{recordId: 1, tasks: [{title:'they'}, {title:'she'}] }
]
const workspacesById = []
workspaces.forEach(w => {
const idx = workspacesById.findIndex(item => item.recordId === w.recordId)
if (idx > -1) {
workspacesById[idx].tasks = [...workspacesById[idx].tasks, ...w.tasks]
} else {
workspacesById.push(w)
}
})
console.log(workspacesById)
I think this is close to what you want
const arr = [
{ recordId: 1, tasks: [{ title: 'me' }, { title: 'we' }] },
{ recordId: 2, tasks: [{ title: 'hi' }, { title: 'it' }] },
{ recordId: 2, tasks: [{ title: 'f' }, { title: 'e' }] },
{ recordId: 2, tasks: [{ title: 'hi' }, { title: 'it' }] },
];
const result = arr.reduce((result, item) => {
if (result[item.recordId]) {
const prevTasks = result[item.recordId];
result[item.recordId].tasks = prevTasks.concat(item.tasks);
} else {
result[item.recordId] = item.tasks;
}
return result;
}, {});
The result will be
{
"1": [
{
"title": "me"
},
{
"title": "we"
}
],
"2": [
{
"title": "hi"
},
{
"title": "it"
}
]
}
Here is your result
let result = [];
for(let i=0; i<workspaces.length; i++) {
let recordFound = false;
if (result.length > 0) {
for(let j=0; j<result.length ; j++) {
if(workspaces[i].recordId === result[j].recordId) {
result[j].tasks = [...result[j].tasks, ...workspaces[i].tasks];
recordFound = true;
}
}
}
if (!recordFound) {
result.push(workspaces[i]);
}
}
console.log(result); //your expected result

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

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