如何基于这个简单对象构建这个复杂的数组
How to build out this complex Array based on this Simple Object
>http://jsfiddle.net/leongaban/tuhgns3q/
我的简单对象:
{
portfolio: "AAPL",
t1_tag1: "1111",
t2_tag1: "2222",
t3_tag1: "3333",
ticker1: "AA",
ticker2: "GOOG",
ticker3: "AAPL"
}
所需的最终结果如下。包含对象数组的数组:
[
0:Object {
tags: [
0:Object {
t1_tag1: "1111"
}
]
ticker: ticker1
},
1:Object {
tags: [
0:Object {
t2_tag2: "2222"
}
]
ticker: ticker2
},
3:Object {
tags: [
0:Object {
t3_tag3: "3333"
}
]
ticker: ticker3
}
]
有没有更简单的方法可以通过_lodash来实现这一点?
以下是我只使用vanilla JavaScript而没有lodash或下划线想到的:
function expand(simple) {
var outerArray = [], innerArray,
outerIndex = 1, innerIndex,
outerObject, innerObject;
while (("ticker" + outerIndex) in simple) {
innerArray = [];
innerIndex = 1;
while (("t" + outerIndex + "_tag" + innerIndex) in simple) {
innerObject = {};
innerObject["t" + outerIndex + "_tag" + innerIndex] = simple["t" + outerIndex + "_tag" + innerIndex];
innerArray.push(innerObject);
innerIndex++;
}
outerObject = {
tags: innerArray,
ticker: simple["ticker" + outerIndex]
};
outerArray.push(outerObject);
outerIndex++;
}
return outerArray;
}
console.log(expand({
portfolio: "AAPL",
t1_tag1: "1111",
t2_tag1: "2222",
t3_tag1: "3333",
ticker1: "AA",
ticker2: "GOOG",
ticker3: "AAPL"
}));
相关文章:
- 使用复杂数组时Jquery自动完成功能不起作用
- 添加到序列化数组中的复杂对象在服务器端始终为 null
- 在javascript中拼接一个复杂的多维数组
- 微风:将项目添加到复杂类型的数组中
- 在数组中使用注释字符构建复杂字符串
- 如何将新的复杂条目添加到 javascript 数组中
- 如何使用 php 制作正则表达式以从以下代码中抓取复杂数组
- 角度JS并将复杂对象数组作为属性传递给指令
- 挖空JS只使复杂对象数组的一个属性可观察
- Angular JS ng重复使用复杂的JSON数据(数组、子数组、子对象)
- 使用复杂数组的Javascript
- 按中的值对数组的复杂数组进行排序
- javascript中的复杂数组
- Jquery,如何循环遍历复杂数组
- 如何循环遍历JSON对象的复杂数组,其中包含数组和动态键
- 从列表创建复杂数组
- Jquery从输入映射复杂数组
- 使用嵌套循环的复杂数组合并
- 了解复杂数组三元运算符
- 如何在复杂数组中转换数组