我有一个扁平的物体,我需要一个分段。下面的代码片段就是一个例子:
var raw = {
"Result[0].Row[0].GUID": "sdfsdfsd",
"Result[1].True": true,
"Result[1].Row[0].Name": "Item 1 name",
"Result[1].Row[0].Type": "3",
"Result[1].Row[0].Active": false,
"Result[1].Row[1].Name": "Item 2 name",
"Result[1].Row[1].Type": "7b",
"Result[1].Row[1].Active": true,
"Result[1].Row[2].Name": "Item 3 name",
"Result[1].Row[2].Type": "qr8",
"Result[1].Row[2].Active": true,
"Result[2].Row[0].Desc": "yaddayaddayadda"
}
我正在尝试清理格式化,我只想处理以Result[1].Row
开头的任何事情。一旦我分离了那个小节,我就想迭代这些行,所以就像......
var i = 0,
goodRows = [];
for (var row in "Result[1].Row Object") {
var cleanObj = {
name: row[i].Name,
type: row[i].Type,
active: row[i].Active
}
goodRows.push(cleanObj)
i++;
}
我遇到的问题是,我甚至无法为这个问题提出一个笨重的解决方案,更不用说干净了。我绝对愿意使用一些第三方库,如lodash,下划线或任何NPM。
首先将对象转换为列表
Object.entries(raw)
然后过滤您的谓词
const isFirstRow = ([key, value]) => key.startsWith('Result[0].Row')
然后映射你的功能
Object.entries(raw)
.filter(isFirstRow)
.map(processRow)
在您的问题中,您只要求文本中的Result [0],但您在示例代码中查找Result [1]。我假设后者是正确的索引。
在此示例中,我们使用正则表达式来解析raw的属性,取出Row索引和属性名称,并使用解析的值创建干净的对象。
const goodRows= [];
const regex = /Result\[1\]\.Row\[(\d+)\]\.(\w+)/
for(var propertyName in raw){
const parsedRow = propertyName.match(regex);
if(parsedRow){
const index = parsedRow[1];
const parsedPropertyName = parsedRow[2];
if(!goodRows[index]){
goodRows[index] = {};
}
goodRows[index][parsedPropertyName] = raw[propertyName];
}
}
console.debug(goodRows);