javascript 从字符串生成对象的非重复数组[已关闭]

8cdiaqws  于 2022-12-21  发布在  Java
关注(0)|答案(6)|浏览(123)
    • 已关闭**。此问题需要超过focused。当前不接受答案。
    • 想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

6天前关闭。
Improve this question
我有绳子。

string = "home/all-videos/blog"

我想从字符串中生成一个数组。

array = [{
    name: "home",
    path: "home"
  }, {
    name: "all-videos",
    path: "home/all-videos"
  }, {
    name: "blog",
    path: "home/all-videos/blog"
  }
]

我该如何在JS中执行此操作?

46scxncf

46scxncf1#

.split("/")返回一个数组,然后你需要创建(3)个对象并填充它们。

var s = string.split("/");
var obj1 = {};
obj1.name = s[1];
///... keep going
vmdwslir

vmdwslir2#

您可以使用Array#reduce
只需将当前项的名称连接到前一项的路径即可计算路径。

const string = "home/all-videos/blog"
const result = string.split('/').reduce((a,c) => {
  const last = a[a.length - 1];
  a.push({name: c, path: last ? last.path + '/' + c : c })
  return a;
}, [])
console.log(result)

精简版:

const string = "home/all-videos/blog"
const result = string.split('/').reduce((a,c) => (a.push({name: c, path: a[a.length - 1] ? a[a.length - 1].path + '/' + c : c}), a), [])
console.log(result)
r7s23pms

r7s23pms3#

您可以使用如下堆栈:

let parts = "home/all-videos/blog".split("/")
let stack = [], array = []

parts.forEach(part => {
    array.push({
      name: part,
      path: [...stack, part].join("/")
    })  
    stack.push(part)
})

console.log(array)
x3naxklr

x3naxklr4#

我会先把它分割成碎片,然后用map的索引把它们重新连接起来。

const string = "home/all-videos/blog"

const fragments = string.split("/");
const result = fragments.map((f,i) => ({name: f, path: fragments.slice(0,i+1).join("/")}));

console.log(result);
vom3gejh

vom3gejh5#

您可以:

const string = 'home/all-videos/blog'
const result = string.split('/').map((item) => {
  return {
    name: item,
    path: string.substring(0, string.indexOf(item) + item.length),
  }
})

console.log(result)
jslywgbw

jslywgbw6#

我设法用这种方法解决了它,希望能有所帮助。

const string = 'home/all-videos/blog'
const newArray = []

let word = ''

for (const letter of string) {
  if (letter === '/') {
    newArray.push({
      name: word,
      path: word,
    })
    word = ''
  }
  if (string.indexOf(letter) === string.length - 1) {
    word += letter
    newArray.push({
      name: word,
      path: word,
    })
    word = ''
  }
  word += letter
}
console.log(newArray)

相关问题