Mapping array of strings into array of specific object - javascript

I have a problem to make an array of strings into objects of url paths (for breadcrumbs)
I have this array :
const array = ['visit', 'schedule', 'validator']
What I tried :
const routeArray = array.map((b) => ({
label: b,
route: `/${b}`,
}))
console.log(routeArray)
result :
[
{label: "visit", route: "/visit"},
{label: "schedule", route: "/schedule"},
{label: "validator", route: "/validator"},
]
what I want to achieve :
[
{label: "visit", route: "/visit"},
{label: "schedule", route: "/visit/schedule"},
{label: "validator", route: "/visit/schedule/validator"}
]
Any help ?

Just concatenate the String while going through the array:
const array = ['visit', 'schedule', 'validator'];
let route = "";
const result = array.map(label => {
route += '/' + label;
return { label, route };
});

Array.prototype.map(), Array.prototype.slice() and Array.prototype.join() can be your best friends, here:
const input = ['visit', 'schedule', 'validator'];
const output = input.map((item, index) => {
return {
label: item,
route: '/' + input.slice(0, index + 1).join('/')
}
});
// test
console.log(output);

Please check this out and let me know if this is what you were looking for:
const array = ['visit', 'schedule', 'validator']
const newArray = array.map((entry, index) => {
const route = [];
for (let i = 0; i < index + 1; i++) {
route.push(array[i]);
}
return {
label: entry,
route: route.join('/'),
};
});
console.log(newArray);
In this approach, I loop through as many elements as the order of the current element of array, pushing them into the route array. When creating the object properties, I join the elements of route separated by '/'.

Here is how we can do this using the reduce method:
const arr = ["visit", "schedule", "validator"];
const res = arr.reduce((acc, curr, idx, self) => {
// Our route property of our needed data structure
const route = `/${self.slice(0, idx)}${idx > 0 ? "/" + curr : curr}`;
// Our new object
const obj = { label: curr, route };
return [...acc, obj];
}, []);
console.log(res);

Can be done using a for loop. You need to have a variable which tracks your incrementing route and persists over loop iterations.
const array = ['visit', 'schedule', 'validator'];
let ansArray = [];
let incrVal = '';
for(let i = 0 ; i < array.length; i++){
let ans = incrVal + '/' + array[i];
ansArray.push({'label' : array[i], 'route' : ans});
incrVal = ans;
}
console.log(ansArray);

const array = ['visit', 'schedule', 'validator'];
const results = array.map((item, index, arr) => {
return {
label: item,
route: '/' + arr.slice(0, index + 1).join('/'),
};
});
console.log(results);

Using reduce array method
const array = ["visit", "schedule", "validator"];
const res = array.reduce((acc, curr, idx, arr) => {
acc.push({
label: curr,
route:'/'+ arr.slice(0, idx + 1).join('/')
})
return acc;
}, []);
console.log(res);

I think this is the shortest way to do this:
const input = ["visit", "schedule", "validator"];
const res = input.map((label, i, arr) => ({
label,
route: '/' + arr.slice(0, i + 1).join("/")
}));
console.log(input);
console.log(res);

Related

Object.keys(data).map(v) not giving the actual key value

I want to convert an object into an array of object but my code give the wrong result like shown below..
// object
data = { user_id : '123' }
// expected result
data = [ { user_id : '123' } ]
// what I get instead
data = [ { v : '123' } ]
my code:
let arr = [];
Object.keys(data).map(v => {
console.log(v, data[v]); // here it shows 'user_id' and '123' as it's supposed to
arr.push({ v:data[v] }); // but here it uses the 'v' as property instead of 'user_id'
});
You need to put v inside a square bracket
const data = {
user_id: '123'
}
let arr = [];
Object.keys(data).map(v => {
arr.push({
[v]: data[v]
});
});
console.log(arr)
Alternatively you can also use Object.entries. You dont need initialize let arr = []; as map will create a new array
const data = {
user_id: '123'
}
const arr = Object.entries(data).map(v => {
return {
[v[0]]: v[1]
}
});
console.log(arr)
when you need to use variable as key in object, you must use [].
Example:
const key = 'user_id'
const obj = {
[key]: 'user'
}
## result
{
'user_id': 'user
}
So change v to [v].
let arr = [];
Object.keys(data).map(v => {
arr.push({ [v]:data[v] }); // replace v to [v]
});

Extracting values out of an array of objects?

I am trying to extract id from the below array of objects and so far I am able to give it a go with the below code but it is showing undefined and cannot get id , would you please check the code and adjust to get id out?
const array = [{
contact: {
id: 1,
email: 'roar#gmail.com',
},
date: '2/4/22'
},
{
contact: {
id: 2,
email: 'grr#gmail.com',
},
date: '2/4/22'
}
]
function extractValue(arr, prop) {
let extractedValue = [];
for (let i = 0; i < arr.length; ++i) {
// extract value from property
extractedValue.push(arr[i][prop]);
}
return extractedValue;
}
const result = extractValue(array, 'contact.id');
console.log(result);
A good way to do this is the Array Map method
This will get all the id's from your array
const result = array.map((val) => val.contact.id)
const extractValue = (array, path) => {
const [first, second] = path.split('.')
if (second) return array.map(obj => obj[first][second])
return array.map(obj => obj[first])
}
const res = extractValue(array, 'contact.id')
console.log(res)
// => [ 1, 2 ]
this will support single and double level nested results
function find(val, arr) {
for (let x of arr)
val = val[x];
return val;
}
function extractValue(arr, prop) {
return array.map(x => find(x, prop.split(".")))
}

unable to add check inside map to filter out details

updating the value only if matches mnemonic for currentTab which is present in items data without changing original items
let items = [{tab:'tab1',info:[{mnemonic:'first',value:'alm'},{mnemonic:'second',value:'jim'}]},
{tab: 'tab2',info:[{mnemonic:'first',value:'kim'},{mnemonic:'second',value:'tim'}]},
{tab:'tab3',info:[{mnemonic:'first',value:'wint'},{mnemonic:'second',value:'telt'}]}]
let expectedOutput = [{tab:'tab1',info:[{mnemonic:'newValue',value:'alm'},{mnemonic:'second',value:'jim'}]},
{tab: 'tab2',info:[{mnemonic:'first',value:'kim'},{mnemonic:'second',value:'tim'}]},
{tab:'tab3',info:[{mnemonic:'first',value:'wint'},{mnemonic:'second',value:'telt'}]}]
let currentTab = 'tab1';
let obj = {mnemonic:'first',value:'newValue'}
const getChecked = ()=> {
const newArr = items
.map(
({ info, ...rest }) => ({
...rest, info: info
})
)
return newArr;
}
const arr = getChecked();
console.log('newArr',arr)
By using Array.map we can achieve this.
let items = [{tab:'tab1',info:[{mnemonic:'first',value:'alm'},{mnemonic:'second',value:'jim'}]},{tab:'tab2',info:[{mnemonic:'first',value:'kim'},{mnemonic:'second',value:'tim'}]},{tab:'tab3',info:[{mnemonic:'first',value:'wint'},{mnemonic:'second',value:'telt'}]}];
let currentTab = 'tab1';
let obj = { mnemonic: 'first', value: 'newValue' };
const updateItems = (items, currentTab, obj) =>{
return items.map(item => {
//check if the provided tab is matching with the item.tab
if(item.tab === currentTab) {
return {
...item,
info: item.info.map(i => ({
...i,
//update the `mnemonic` if provided object's mnemonic is matching with the item's mnemonic
...(i.mnemonic === obj.mnemonic && { mnemonic: obj.value })
}))
}
} else return {...item}
})
}
console.log(updateItems(items, currentTab, obj))
.as-console-wrapper {
max-height: 100% !important;
}

I want output in specified format

I am trying to create timeline map using echarts js. I hope I am not able to figure out how to create 'optiosn' as required. Using these code, I obtained 'option' as picture below.
import axios from 'axios'
const data = []
const date= []
let options= []
axios.get('https://data.nepalcorona.info/api/v1/covid').then((res) => {
const array = res.data
const groups = array.reduce((groups, info) =>{
const date = info.reportedOn;
if (!groups[date]) {
groups[date] = [];
}
groups[date].push(info);
return groups;
}, {});
const groupingDate = Object.keys(groups).map((date) =>{
return{
date: date,
infos: groups[date]
};
})
const sortedData = groupingDate.sort((a,b) => {
var dateA = new Date(a.date) , dateB = new Date(b.date)
return dateA - dateB
})
for(let i=0; i< sortedData.length; i++) {
date.push(sortedData[i].date)
const array = sortedData[i].infos
data.push(array)
}
const points= [];
const newlist = data.map(x => {
points.push([x[0].point.coordinates[0], x[0].point.coordinates[1], x[0].age]);
return {
series:{
data: points.slice(0)
}
}
})
options.push(newlist)
console.log(options)
})
export default {
...
options: [options][0],
...
}
The result of this is obtained as below:
But i dont want an unnecessary array as it is obtained. I want options as below:
options: Object
---baseOption: Object
---options: Array[67]
I hope you can understand what i am saying.
use the spread operator in your third last line as following
options.push(...newlist)
instead of
options.push(newlist)

issue with spread operator in javascript

I want to rewrite an array and to get a new one at the final.
This is my code:
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => {
const r = {
...arr,
power:2
}
return r
})
console.log(newArr)
Now i get the wrong result, because one every iteration, the new array grow with a copy of the first array:
const r = {
...arr,
power:2
}
How to get the next result?
{
type:"Fiat", model:"500", color:"white", power: 2
},
{
type:"ford", model:"5300", color:"gray", power: 2
}
You are spreading arr .You need to spread i which is the object inside the array.
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => {
const r = {
...i,
power:2
}
return r;
})
console.log(newArr)
With array function you can implicitly
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => ({...i, power: 2}));
console.log(newArr)
You need to spread the current object that you are getting as:
const newArr = arr.map(i => ({ ...i, power: 2 }));
You want to do this, you are spreading arr and should be spreading the array getting passed to map (e.g. i):
const newArr = arr.map(i => {
const r = {
...i,
power:2
}
return r
})

Categories