将字符串数组转换为对象
Transform Array of Strings to Objects
我有一个字符串数组,每个字符串都包含以逗号分隔的值。
我想将其转换为对象数组。
比如我有:
var myarray = [
"a1,b1,c1,d1",
"a2,b2,c2,d2",
"a3,b3,c3,d3"
]
... 最终应为:
[
{
"field1": "a1",
"field2": "b1",
"field3": "c1",
"field3": "d1"
},
{
"field1": "a2",
"field2": "b2",
"field3": "c2",
"field2": "d2"
},
{
"field1": "a3",
"field2": "b3",
"field3": "c3",
"field3": "d3"
},
]
我尝试过各种方法,例如 Object.assign 和展开运算符。但似乎必须有一种更简单的方法来使用解构或其他方法来做到这一点。
var myarray = [
"a1,b1,c1,d1",
"a2,b2,c2,d2",
"a3,b3,c3,d3"
];
const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
result['field' + (index + 1)] = splitItem;
return result;
}, {}));
console.log(makeProperties(myarray));
这里有一个使用单词表示数字的演示
var myarray = [
"a1,b1,c1,d1",
"a2,b2,c2,d2",
"a3,b3,c3,d3"
];
const numbers = ['one', 'two', 'three', 'four'];
const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
result[numbers[index]] = splitItem;
return result;
}, {}));
console.log(makeProperties(myarray));
您可以通过将数组映射到它们的值并将默认属性替换为新属性来制作双 map。
var myarray = ["a1,b1,c1,d1", "a2,b2,c2,d2", "a3,b3,c3,d3"];
const fromArrayToObjects = (array) =>
array.map((value, index) => {
const o = Object.assign({}, value.split(","));
Object.keys(o).map((key, i) => {
Object.defineProperty(
o,
"field" + (i + 1),
Object.getOwnPropertyDescriptor(o, key)
);
delete o[key];
});
return o;
});
console.log(fromArrayToObjects(myarray));
我有一个字符串数组,每个字符串都包含以逗号分隔的值。
我想将其转换为对象数组。
比如我有:
var myarray = [
"a1,b1,c1,d1",
"a2,b2,c2,d2",
"a3,b3,c3,d3"
]
... 最终应为:
[
{
"field1": "a1",
"field2": "b1",
"field3": "c1",
"field3": "d1"
},
{
"field1": "a2",
"field2": "b2",
"field3": "c2",
"field2": "d2"
},
{
"field1": "a3",
"field2": "b3",
"field3": "c3",
"field3": "d3"
},
]
我尝试过各种方法,例如 Object.assign 和展开运算符。但似乎必须有一种更简单的方法来使用解构或其他方法来做到这一点。
var myarray = [
"a1,b1,c1,d1",
"a2,b2,c2,d2",
"a3,b3,c3,d3"
];
const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
result['field' + (index + 1)] = splitItem;
return result;
}, {}));
console.log(makeProperties(myarray));
这里有一个使用单词表示数字的演示
var myarray = [
"a1,b1,c1,d1",
"a2,b2,c2,d2",
"a3,b3,c3,d3"
];
const numbers = ['one', 'two', 'three', 'four'];
const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
result[numbers[index]] = splitItem;
return result;
}, {}));
console.log(makeProperties(myarray));
您可以通过将数组映射到它们的值并将默认属性替换为新属性来制作双 map。
var myarray = ["a1,b1,c1,d1", "a2,b2,c2,d2", "a3,b3,c3,d3"];
const fromArrayToObjects = (array) =>
array.map((value, index) => {
const o = Object.assign({}, value.split(","));
Object.keys(o).map((key, i) => {
Object.defineProperty(
o,
"field" + (i + 1),
Object.getOwnPropertyDescriptor(o, key)
);
delete o[key];
});
return o;
});
console.log(fromArrayToObjects(myarray));