L
L
lavezzi12018-03-13 06:48:16
JavaScript
lavezzi1, 2018-03-13 06:48:16

How can the previous value of an object be added to the current value?

Hello. There is a type path: you need to get an array of objects from it:const path = 'dir1/dir2/dir3/dir4/';

const arr = [
  { key: 'dir1', path: 'dir1/' },
  { key: 'dir2', path: 'dir1/dir2/' },
  { key: 'dir3', path: 'dir1/dir2/dir3/' },
  { key: 'dir4', path: 'dir1/dir2/dir3/dir4/' },
]

How can this be implemented?
My attempt is https://jsfiddle.net/1dh5db4d/30/

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
alvvi, 2018-03-13
@lavezzi1

const path = 'dir1/dir2/dir3/dir4/';
const result = 
  path
     .split('/')
     .slice(0,-1)
     .map((key, i, self) => ({key, path: self.slice(0, i+1).join('/') + '/'});

D
Dmitry Eremin, 2018-03-13
@EreminD

const paths = path.split("/")
    paths.forEach(function (item) {
      if(item) arr.push(
        {key: item, path: path.substring(0, path.indexOf(item)) + item})
    })

D
Dmitry, 2018-03-13
@demon416nds

why so many constants and unnecessary movements?

const path = 'dir1/dir2/dir3/dir4/';
const arrOfPath = path.split('/');
crumbs=[];
for(var i=0;i<arrOfPath.length-1;i++)
{crumbs[i]='';
for(var j=0;j<=i;j++)
{crumbs[i]=crumbs[i]+arrOfPath[j];}}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question