我有两个数组[14, 20 , 40 , 40]
和["6:28 PM","7:28 PM","8:28 PM","9:28 PM"]
。
我想把它作为
[{x:14,y:"6:28 PM"},
{x:20,y:"7:28 PM"},
{x:40,y:"8:28 PM"},
{x:40,y:"9:28 PM"}]
我试图用另一个数组,例如a.push(x:values,y:time)
推送数组,但这没有用。
答案 0 :(得分:2)
const ids = [14, 20 , 40 , 40];
const times = ["6:28 PM","7:28 PM","8:28 PM","9:28 PM"];
const result = ids.map((id, i) => ({ x: id, y: times[i] }));
console.log(result);
与Angular没有关系。
答案 1 :(得分:1)
使用任意数量的属性,您可以将名称为数组的键作为键,并使用简短的属性对象,并根据给定的数据构建新的数据集。
它与一个对象一起工作,该对象将具有更高键名的数组作为属性(short hand properties)。
public int getCameraCount(){ CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); try { String[] strings = manager.getCameraIdList(); return strings.length; } catch (CameraAccessException e) { e.printStackTrace(); return 0; } }
从该对象中获取键/值对(值是数组)的数组,并用
Array#reduce
进行缩减。{ value, time }
这是通过将数组作为起始值并使用
Array#forEach
用值迭代数组来实现的。result = Object .entries({ value, time }) .reduce( ... )
在分配之前,将检查给定索引处的结果集,如果不存在,则将一个新对象作为默认值。
(r, [k, a]) => (a.forEach((v, i) => (r[i] = r[i] || {})[k] = v), r), // callback [] // start value
使用键
r[i] = r[i] || {}
,分配实际值。k
结果是一个对象数组,其中包含来自命名变量的键和数组的值。
(r[i] = r[i] || {})[k] = v
var value = [14, 20, 40, 40],
time = ["6:28 PM", "7:28 PM", "8:28 PM", "9:28 PM"],
result = Object
.entries({ value, time })
.reduce((r, [k, a]) => (a.forEach((v, i) => (r[i] = r[i] || {})[k] = v), r), []);
console.log(result);
答案 2 :(得分:0)
const values = [14, 20 , 40 , 40];
const times = ["6:28 PM", "7:28 PM", "8:28 PM", "9:28 PM"];
const myObj = values.map((value, index) => ({
x: value,
y: times[index]
}));
答案 3 :(得分:0)
let a=[14, 20 , 40 , 40];
let b=["6:28 PM","7:28 PM","8:28 PM","9:28 PM"];
let result = a.map((t,index)=>Object.assign({x:t,y:b[index]}));
结果将如您所愿
答案 4 :(得分:0)
let newArr = [];
a = [14, 20 , 40 , 40]
b = ["6:28 PM","7:28 PM","8:28 PM","9:28 PM"]
for(i=0;i<a.length;i++){
let obj = {x: a[i], y: b[i]}
newArr.push(obj)
}
答案 5 :(得分:0)
受Pythons zip function的启发。像夹克上的拉链一样工作:
function zip(a, b) {
var arr = [];
for (var key in a) { arr.push([a[key], b[key]]); }
return arr;
}
const ids = [14, 20, 40, 40];
const times = ["6:28 PM", "7:28 PM", "8:28 PM", "9:28 PM"];
const zipped = zip(ids, times)
答案 6 :(得分:0)
function processor(values, times){
// Map function use two array value and return processed array of objects
return values.map((value, index) => ({
x: value,
y: times[index]
}));
}
// Pass two array as arguments for two which you want processed
processor([14, 20 , 40 , 40], ["6:28 PM", "7:28 PM", "8:28 PM", "9:28 PM"]);
答案 7 :(得分:0)
get_index(s)