Extracting array value from nested array of objects - javascript

Hi guys i have created the following array of objects . And to be honest i am a little bit lost . But please take a look and help me out
[
{
name: "bananaLight",
bananaDefinition: [
{
bananaRef: 'startBanana',
title: 'Start Banana'
},
{
bananaRef: 'endBanana',
title: 'End Banana'
}
]
},
{
name: "bananaFull",
bananaDefinition: [
{
bananaRef: 'bananaSize'
title: 'Banana Size'
},
{
bananaRef: 'startBanana',
title: 'Start Banana'
},
{
bananaRef: 'endBanana',
title: 'End Banana'
}
]
}
]
The idea here is to fetch the array of bananaDefinition bounded with the name bananaLight

You can use find():
const bananaArray = [{
name: "bananaLight",
bananaDefinition: [{
bananaRef: 'startBanana',
title: 'Start Banana'
}, {
bananaRef: 'endBanana',
title: 'End Banana'
}]
}, {
name: "bananaFull",
bananaDefinition: [{
bananaRef: 'bananaSize',
title: 'Banana Size'
}, {
bananaRef: 'startBanana',
title: 'Start Banana'
}, {
bananaRef: 'endBanana',
title: 'End Banana'
}]
}];
const result = bananaArray.find(v => v.name === 'bananaLight').bananaDefinition;
console.log(result);

Based on what you want to do you might want to get it from different ways. here is some of them:
const dataArray = [
{
name: "bananaLight",
bananaDefinition: [
{
bananaRef: "startBanana",
title: "Start Banana",
},
{
bananaRef: "endBanana",
title: "End Banana",
},
],
},
{
name: "bananaFull",
bananaDefinition: [
{
bananaRef: "bananaSize",
title: "Banana Size",
},
{
bananaRef: "startBanana",
title: "Start Banana",
},
{
bananaRef: "endBanana",
title: "End Banana",
},
],
},
];
1
const bananaLightFind = dataArray.find((item) => item.name === "bananaLight");
2
const foundIndex = dataArray.findIndex(item => item.name === "bananaLight")
const bananaLightFindIndex = dataArray[foundIndex];
3
let bananaLightLoop;
dataArray.forEach((item) => {
if (item.name === "bananaLight") {
bananaLightLoop = item;
}
});

Related

How do I create arrays from array in this case

I am trying to create multiple arrays of objects with each keys inside the object.
How can I generate my expected output (shown below the initial array)?
Initial array:
[{
title: 'Linus tech tips',
name: 'Linus',
id: 'SA946',
},
{
title: 'Linus tech tips',
name: 'Colton',
id: 'SA947',
}
];
Expected output:
[{
text: 'Linus tech tips',
}, {
text: 'Linus',
}, {
text: 'SA946',
}, ],
[{
text: 'Linus tech tips',
}, {
text: 'Colton',
}, {
text: 'SA947',
}, ],
You can use array.map to achieve that. Please have a look:
const initial = [
{
title: 'Linus tech tips',
name: 'Linus',
id: 'SA946',
},
{
title: 'Linus tech tips',
name: 'Colton',
id: 'SA947',
},
];
const expected = initial.map(
(item) => Object.values(item).map(
(itemValue) => ({ text: itemValue }),
),
);
console.log(expected);
You need to iterate over the keys, then flatten the array.
[{
title: 'Linus tech tips',
name: 'Linus',
id: 'SA946',
},
{
title: 'Linus tech tips',
name: 'Colton',
id: 'SA947',
}].map(
item => {
return Object.keys(item).map(
key => {
return {text: item[key]}
}
)
}
).flat()
[
{
"text": "Linus tech tips"
},
{
"text": "Linus"
},
{
"text": "SA946"
},
{
"text": "Linus tech tips"
},
{
"text": "Colton"
},
{
"text": "SA947"
}
]
Or, if you want to have the items separated, do not use flat() at the end:
[
[
{
"text": "Linus tech tips"
},
{
"text": "Linus"
},
{
"text": "SA946"
}
],
[
{
"text": "Linus tech tips"
},
{
"text": "Colton"
},
{
"text": "SA947"
}
]
]

Mapping array in javacript app in a react app

This is my array, I'm working on react app
const categoryObj = [
{
id: "463e989a-c4f2-4616-85c5-0cb610c5fff0",
name: "Women",
subCategory: [
{
id: "91ba7308-b68e-4d0c-85d8-0cc8272c6bc8",
name: "All",
icon: "AllIcon"
},
{
id: "0e0712c5-0b5a-4d4e-acf5-3d7faf2caa2a",
name: "Clothes",
icon: "ClothesIcon",
sections: [
{
id: "9b7a7a58-04a1-4aba-ba68-0e6b1390021e",
name: "All",
href: "Women/Clothes/All".split(' ').join('-').trim().toLowerCase()
}
]
}
]
}
]
how can I access "women" in this array ? (I have many items like "women" this is just a sample of a large array. if you can suggest a mapping method it's better.)
You can map through it to get the name value in this way:
categoryObj.map((category) => category.name)
const categoryObj = [
{
id: "463e989a-c4f2-4616-85c5-0cb610c5fff0",
name: "Women",
subCategory: [
{
id: "91ba7308-b68e-4d0c-85d8-0cc8272c6bc8",
name: "All",
icon: "AllIcon"
},
{
id: "0e0712c5-0b5a-4d4e-acf5-3d7faf2caa2a",
name: "Clothes",
icon: "ClothesIcon",
sections: [
{
id: "9b7a7a58-04a1-4aba-ba68-0e6b1390021e",
name: "All",
href: "Women/Clothes/All".split(' ').join('-').trim().toLowerCase()
}
]
}
]
},
{
id: "463e989a-c4f2-4616-85c5-0cb610c5fff0",
name: "Men",
subCategory: [
{
id: "91ba7308-b68e-4d0c-85d8-0cc8272c6bc8",
name: "All",
icon: "AllIcon"
},
{
id: "0e0712c5-0b5a-4d4e-acf5-3d7faf2caa2a",
name: "Clothes",
icon: "ClothesIcon",
sections: [
{
id: "9b7a7a58-04a1-4aba-ba68-0e6b1390021e",
name: "All",
href: "Women/Clothes/All".split(' ').join('-').trim().toLowerCase()
}
]
}
]
},
{
id: "463e989a-c4f2-4616-85c5-0cb610c5fff0",
name: "Children",
subCategory: [
{
id: "91ba7308-b68e-4d0c-85d8-0cc8272c6bc8",
name: "All",
icon: "AllIcon"
},
{
id: "0e0712c5-0b5a-4d4e-acf5-3d7faf2caa2a",
name: "Clothes",
icon: "ClothesIcon",
sections: [
{
id: "9b7a7a58-04a1-4aba-ba68-0e6b1390021e",
name: "All",
href: "Women/Clothes/All".split(' ').join('-').trim().toLowerCase()
}
]
}
]
}
]
const result = categoryObj.filter(obj => obj.name === 'Women')
console.log('multi objects :', result)
// if unique with name
const resultUnique = categoryObj.find(obj => obj.name === 'Women')
console.log('unique object :', resultUnique)
This object contains an object and have another variations as sub. If you want to access first name,
categoryObj.map((it) => {
//You can handle it like this
console.log(it.name)
})
But if you want all name of all subCategory,
categoryObj[0].subCategory.map((cat) => {
//You can handle it like this
console.log(cat.name)
})
You have same object-type in and out.
const res = categoryObj.filter(item=>item.name === 'Women');

javascript object multi-dimensional to array one dimenstional [duplicate]

This question already has answers here:
Generify transformation of hierarchical array into a flat array
(2 answers)
Closed 3 years ago.
I have variable rawData like this:
let rawData = [
{
title: '1',
result: '1',
child: [
{
title: '1-1',
result: '1-1',
child: [
{
title: '1-1-1',
result: '1-1-1',
child: [
{
title: '1-1-1-1',
result: '1-1-1-1',
child: [
{
title: '1-1-1-1-1',
result: '1-1-1-1-1',
},
],
},
{
title: '1-1-1-2',
result: '1-1-1-2',
},
{
title: '1-1-1-3',
result: '1-1-1-3',
},
],
},
],
},
],
},
];
and with my function. it runs as expected, here's my function:
let normalizeArray = [];
function test(array) {
for (const key in array) {
if (array.hasOwnProperty(key)) {
const element = array[key];
if (element.hasOwnProperty('child')) {
test(element.child);
delete element.child;
normalizeArray.unshift(Object.assign({}, element));
} else {
normalizeArray.push(Object.assign({}, element));
}
}
}
}
and return (expected):
[
{ title: '1', result: '1' },
{ title: '1-1', result: '1-1' },
{ title: '1-1-1', result: '1-1-1' },
{ title: '1-1-1-1', result: '1-1-1-1' },
{ title: '1-1-1-1-1', result: '1-1-1-1-1' },
{ title: '1-1-1-2', result: '1-1-1-2' },
{ title: '1-1-1-3', result: '1-1-1-3' },
];
But, if the rawData like this:
let rawData = [
{
title: '1',
result: '1',
child: [
{
title: '1-1',
result: '1-1',
child: [
{
title: '1-1-1',
result: '1-1-1',
child: [
{
title: '1-1-1-1',
result: '1-1-1-1',
child: [
{
title: '1-1-1-1-1',
result: '1-1-1-1-1',
},
],
},
{
title: '1-1-1-2',
result: '1-1-1-2',
},
{
title: '1-1-1-3',
result: '1-1-1-3',
},
],
},
],
},
],
},
{
title: '2',
result: '2',
child: [
{
title: '2-2',
result: '2-2',
},
],
},
{
title: '3',
result: '3',
},
];
with my function, it return :
[
{ title: '2', result: '2' },
{ title: '1', result: '1' },
{ title: '1-1', result: '1-1' },
{ title: '1-1-1', result: '1-1-1' },
{ title: '1-1-1-1', result: '1-1-1-1' },
{ title: '1-1-1-1-1', result: '1-1-1-1-1' },
{ title: '1-1-1-2', result: '1-1-1-2' },
{ title: '1-1-1-3', result: '1-1-1-3' },
{ title: '2-2', result: '2-2' },
{ title: '3', result: '3' },
];
How I could got a result like this:
[
{ title: '1', result: '1' },
{ title: '1-1', result: '1-1' },
{ title: '1-1-1', result: '1-1-1' },
{ title: '1-1-1-1', result: '1-1-1-1' },
{ title: '1-1-1-1-1', result: '1-1-1-1-1' },
{ title: '1-1-1-2', result: '1-1-1-2' },
{ title: '1-1-1-3', result: '1-1-1-3' },
{ title: '2', result: '2' },
{ title: '2-2', result: '2-2' },
{ title: '3', result: '3' },
];
And if you could help me to produce leaner code, feel free to help me. I'm still new in javascript
Instead of deleting/shifting/unshifting, you can extract the properties from the array item immediately with destructuring. Push the title and result to the result array as an object, then do a recursive call if child exists. This way, the result array will be the output of an ordinary depth-first strategy:
function doFlat(inputArr, resultsArr = []) {
for (const { child, title, result } of inputArr) {
resultsArr.push({ title, result });
if (child) {
doFlat(child, resultsArr);
}
}
return resultsArr;
}
By putting the results array as a default parameter which gets passed along to every recursive call, you only ever create one array, which is more efficient than creating a new array for every function call and then iterating over it in its caller.
function doFlat(inputArr, resultsArr = []) {
for (const { child, title, result } of inputArr) {
resultsArr.push({ title, result });
if (child) {
doFlat(child, resultsArr);
}
}
return resultsArr;
}
let rawData = [
{
title: '1',
result: '1',
child: [
{
title: '1-1',
result: '1-1',
child: [
{
title: '1-1-1',
result: '1-1-1',
child: [
{
title: '1-1-1-1',
result: '1-1-1-1',
child: [
{
title: '1-1-1-1-1',
result: '1-1-1-1-1',
},
],
},
{
title: '1-1-1-2',
result: '1-1-1-2',
},
{
title: '1-1-1-3',
result: '1-1-1-3',
},
],
},
],
},
],
},
{
title: '2',
result: '2',
child: [
{
title: '2-2',
result: '2-2',
},
],
},
{
title: '3-3',
result: '3-3',
},
];
console.log(doFlat(rawData));
It could get clean looking with spread operator and recursion
function flatten(dataArray) {
const result = [];
dataArray.map(d => {
const { child, ...rest } = d;
result.push(rest);
if(child && child.length) result.push(...flatten(child));
});
return result;
}
console.log(flatten(rawData));
Hope it helps

React: group by multidimensional array object by value in component

How to group multidimensional array objects by value in the component.
I need to group array by page and get the text for every page. I tray to use the map and reduce it but don't get good results. I work on react-native project. JS function groups doesn't work for some reason.
What is the best way to write code for this array?
I have this array:
[
{
number: 1,
englishName: 'Name 1',
items: [
{
text: 'Some text',
page: 1,
},
{
text: 'Some text',
page: 1,
},
],
},
{
number: 2,
englishName: 'Name 2',
items: [
{
text: 'Some text',
page: 2,
},
{
text: 'Some text',
page: 2,
},
],
},
{
number: 3,
englishName: 'Name 3',
items: [
{
text: 'Some text',
page: 3,
},
{
text: 'Some text',
page: 4,
},
],
},
]
I need an array like this
[
{
'page 1': [
{
text: 'Some text',
englishName: 'Name 1',
},
{
text: 'Some text',
englishName: 'Name 2',
},
],
},
{
'page 2': [
{
text: 'Some text',
englishName: 'Name 2',
},
{
text: 'Some text',
englishName: 'Name 2',
},
],
},
....
]
Seems like this will work for you.
This will give you an object:
const allPages = array.reduce((acc, curr) => {
curr.items.forEach((page) => {
var pageKey = `page ${page.page}`
if(!acc[pageKey]){
acc[pageKey] = []
}
acc[pageKey].push({ text: page.text, englishName: curr.englishName })
})
return acc
}, {})
You can convert that object into an array as well:
const finalArr = Object.entries(allPages).map(([page, array]) => {
return {
[page]: array
}
})
See example:
var array = [{
"number": 1,
"englishName": "Name 1",
"items": [
{
"text": "Some text",
"page": 1,
},
{
"text": "Some text",
"page": 1,
}
]
},
{
"number": 2,
"englishName": "Name 2",
"items": [
{
"text": "Some text",
"page": 2,
},
{
"text": "Some text",
"page": 2,
}
]
},
{
"number": 3,
"englishName": "Name 3",
"items": [
{
"text": "Some text",
"page": 3,
},
{
"text": "Some text",
"page": 4,
}
]
}
]
const allPages = array.reduce((acc, curr) => {
curr.items.forEach((page) => {
var pageKey = `page ${page.page}`
if(!acc[pageKey]){
acc[pageKey] = []
}
acc[pageKey].push({ text: page.text, englishName: curr.englishName })
})
return acc
}, {})
const finalArr = Object.entries(allPages).map(([page, array]) => {
return {
[page]: array
}
})
console.log(allPages)
console.log(finalArr)

Build a directory tree from an object

Having an array of items with the following format:
[ { path: '/Folder 1/Folder 1.1',
name: 'Folder 1.1.1',
id: 'Fi6CsP4RWFutOZKsIDoYMSfBPQb-A-lj3C4Jc_zZoG0' },
{ path: '/Folder 1',
name: 'Folder 1.2',
id: 'c2dTN3CgBr9Xik8jdpBkfzR6wZ00oGTX3IbfXrfFujM' },
{ path: '/Folder 1',
name: 'Folder 1.1',
id: 'WmKaOZhzpubcunNNoxbUnqfSYVuNQZDNC852KDJK_G8' },
{ path: '/',
name: 'Folder 1',
id: 'aNRvIvCLyNOgLOmZVzFhoOiZMAz3-p87kBFIGSQS2Yg' },
{ path: '/',
name: 'Folder 2',
id: 'S4FkkQ3hgLTVedIrlSBqe2_1DhrrnLx5szk7-9Wv3X8' } ]
It is possible to take it to a format like the following
var dir = {
"directory": [{
"text": "Folder 1",
"id": 'aNRvIvCLyNOgLOmZVzFhoOiZMAz3-p87kBFIGSQS2Yg',
"nodes": [{
"text": "Folder 1.1",
"id": 'WmKaOZhzpubcunNNoxbUnqfSYVuNQZDNC852KDJK_G8',
"nodes": [{
"text": "Folder 1.1.1",
"id": 'Fi6CsP4RWFutOZKsIDoYMSfBPQb-A-lj3C4Jc_zZoG0'
}]
}, {
"text": "Folder 1.2",
"id": 'c2dTN3CgBr9Xik8jdpBkfzR6wZ00oGTX3IbfXrfFujM'
}]
},
{
"text": "Folder 2",
"id": 'S4FkkQ3hgLTVedIrlSBqe2_1DhrrnLx5szk7-9Wv3X8'
}
]
};
Graphically
Tree
I was thinking using recursion, but I still have not been able to do it.
Here's a non-recursive solution that works by first building a tree, then transforming the tree into the desired structure.
The reason for the first step is due to the slowness of iterating over node arrays in linear time and assumes no order of the flat input array. Performing lookups on an object tree structure speeds up and simplifies the process, making the result tree easy to build in a single traversal.
const treeify = data =>
data.reduce((a, e) => {
let level = a;
e.path.split("/")
.filter(e => e)
.forEach(dir => {
if (!(dir in level)) {
level[dir] = {nodes: {}};
}
level = level[dir].nodes;
})
;
if (e.name in level) {
level[e.name] = {
text: e.name,
id: e.id,
nodes: level[e.name].nodes
};
}
else {
level[e.name] = {text: e.name, id: e.id};
}
return a;
}, {})
;
const format = tree => {
const result = [];
const stack = [[result, tree]];
while (stack.length) {
const [res, curr] = stack.pop();
for (const k in curr) {
const o = {
id: curr[k].id,
text: curr[k].text
};
res.push(o);
if (curr[k].nodes) {
o.nodes = [];
stack.push([o.nodes, curr[k].nodes]);
}
}
}
return {directory: result};
};
const data = [
{
path: '/Folder 1/Folder 1.1',
name: 'Folder 1.1.1',
id: 'Fi6CsP4RWFutOZKsIDoYMSfBPQb-A-lj3C4Jc_zZoG0'
},
{
path: '/Folder 1',
name: 'Folder 1.2',
id: 'c2dTN3CgBr9Xik8jdpBkfzR6wZ00oGTX3IbfXrfFujM'
},
{
path: '/Folder 1',
name: 'Folder 1.1',
id: 'WmKaOZhzpubcunNNoxbUnqfSYVuNQZDNC852KDJK_G8'
},
{
path: '/',
name: 'Folder 1',
id: 'aNRvIvCLyNOgLOmZVzFhoOiZMAz3-p87kBFIGSQS2Yg'
},
{
path: '/',
name: 'Folder 2',
id: 'S4FkkQ3hgLTVedIrlSBqe2_1DhrrnLx5szk7-9Wv3X8'
}
];
console.log(format(treeify(data)));

Categories

Resources