我有一个包含iPhone
模型的元素数组和其后的4个值,例如:
const arr = ['ip6s+', '35', '15', '10', '10', 'ip7', '40', '20', '15', '15']
我想把它变成一个看起来像这样的对象:
const Obj = {
'ip6s+': ['35', '15', '10', '10'],
'ip7+' : ['90', '60', '35', '30']
}
第一个对象是手机型号,第四个对象是它的值。该怎么做?
答案 0 :(得分:5)
您可以使用slice
:
const arr = ['ip6s+', '35', '15', '10', '10','ip7', '40', '20', '15','15'];
const obj = {};
const n = 4; // the number of values after the model name
for (var i = 0; i < arr.length; i += n + 1) {
obj[arr[i]] = arr.slice(i + 1, i + n + 1);
}
console.log(obj);
答案 1 :(得分:1)
您也可以使用reduce()
const arr = ['ip6s+', '35', '15', '10', '10','ip7', '40', '20', '15','15']
let lastCurr = null;
const result = arr.reduce( ( res, curr, ix ) => {
if( 0 == ix % 5 ){
res[ curr ] = [];
lastCurr = curr;
}else
res[ lastCurr ].push( curr );
return res;
}, {} )
答案 2 :(得分:1)
如果始终将键设置为isNaN
,并且第一个值始终与键相对应,那么您将无法像这样进行操作,如果两个键之间的元素数是动态的,则这将更加动态>
const arr = ['ip6s+', '35', '15', '10', '10', 'ip7', '40', '20', '15', '15']
let getDesiredFormat = (arr) => {
let currentKey = arr[0]
let final = arr.reduce((op, inp) => {
if (isNaN(inp)) {
op[inp] = []
currentKey = inp
} else {
op[currentKey].push(inp)
}
return op
}, {})
return final
}
console.log(getDesiredFormat(arr))
答案 3 :(得分:1)
如果数组以以“ ip”开头的项目开头,并且以此为对象中新键的触发器,则可以使用startswith。
这允许在ip后添加可变数量的项目。
const arr = ['ip6s+', '35', '15', '10', '10', 'ip7', '40', '20', '15', '15'];
const obj = {};
let currKey = arr.slice(0, 1);
arr.forEach(s => s.startsWith("ip") ? (currKey = s, obj[s] = []) : obj[currKey].push(s));
console.log(obj);
答案 4 :(得分:0)
使用slice
方法,无论数组中有多少个元素,以下示例也应起作用:
如果在
'ip6s+'
前,但在'ip6s+'
前,'ip7'
必须总是之前,必须有元素。
const arr = ['some', 'elemnts', 'in', 'front', 'ip6s+', '35', '15', 'abc', '80', '58', '10', '10', 'ip7', '40', '20', '15', '15', '100', 'xyz'],
l = arr.length,
ip6sIndex = arr.indexOf('ip6s+'),
ip7Index = arr.indexOf('ip7'),
obj = {};
obj[arr[ip6sIndex]] = arr.slice(ip6sIndex + 1, ip7Index); /** get the items after 'ip6s+' **/
obj[arr[ip7Index]] = arr.slice(-(l - ip7Index) + 1); /** get the items after 'ip7' **/
console.log(obj);