[英]JavaScript: Split objects in array based on space in object property
In JavaScript, let's say I have an array like this:在 JavaScript 中,假设我有一个这样的数组:
[{display:"Foo"},{display:"Bar", field: {"Baz"}},{display:{"Baz Foo"}},{display: "Foo Bar", field: "Bar"}]
and want to convert it into this:并想将其转换为:
[{display:"Foo"},{display:"Bar", field: {"Baz"}},{display:{"Baz"}},{display:{"Foo"}},{display: "Foo", field: "Bar"},{display: "Bar", field: "Bar"}]
. [{display:"Foo"},{display:"Bar", field: {"Baz"}},{display:{"Baz"}},{display:{"Foo"}},{display: "Foo", field: "Bar"},{display: "Bar", field: "Bar"}]
。
In other words, split the objects that contain space in the display field into two objects and keep the field property as it is.也就是说,将显示字段中包含空间的对象拆分为两个对象,并保持字段属性不变。
I feel like it should be some simple solution to this, but I just don't get it right.我觉得这应该是一些简单的解决方案,但我就是不正确。 Does anyone know how I can achieve this?有谁知道我怎么能做到这一点?
try this尝试这个
const arr = [{display:"Foo"},{display:"Bar", field: "Baz"},{display:"Baz Foo"},{display: "Foo Bar", field: "Bar"}]
const newArr = arr.reduce((acc, cur) => {
const { field, display } = cur
const newObjs = display.split(" ").map(dis => ({ display: dis, field }));
acc = acc.concat(newObjs)
return acc
}, [])
This works:这有效:
const input = [ {display:"Foo"}, {display:"Bar", field: "Baz"}, {display:"Baz Foo"}, {display:"Foo Bar", field: "Bar"} ] const output = input.map((entry) => entry.display.split(/\s+/g). map((part) => ({...entry, display: part})) ).flat() console.log(output)
Note that split(/\s+/g)
splits at one or more white-spaces, eg "hello world"
results in ["hello", "world"]
.请注意split(/\s+/g)
在一个或多个空格处拆分,例如"hello world"
会导致["hello", "world"]
。 If you do not want this, change to split(" ")
, the result would then be ["hello", "", "", "", "world"]
如果您不希望这样,请更改为split(" ")
,结果将是["hello", "", "", "", "world"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.