javascript Javascript循环遍历对象数组并取两个值并插入新的对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48666927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript loop through array of objects and take two values and insert into new array of objects
提问by Kiow
I have a array of objects that looks like this:
我有一个看起来像这样的对象数组:
rows [
{ id: 3,
title: "sometitle",
catid: 55,
img: "file" },
{ id: 4,
title: "sometitle",
catid: 55,
img: "file" },
{ id: 5,
title: "sometitle",
catid: 55,
img: "file" },
]
What I now are trying to do is to loop through the array of object and take two values (id and img) from each object and insert it into a new array of object so it ends up looking like this:
我现在要做的是遍历对象数组并从每个对象中获取两个值(id 和 img)并将其插入到一个新的对象数组中,因此它最终看起来像这样:
newArr [
{ id: 3,
img: "file" },
{ id: 4,
img: "file" },
{ id: 5,
img: "file" },
]
回答by Dipu
You can easily do this using map.
您可以使用map.
var rows = [
{ id: 3,
title: "sometitle",
catid: 55,
img: "file" },
{ id: 4,
title: "sometitle",
catid: 55,
img: "file" },
{ id: 5,
title: "sometitle",
catid: 55,
img: "file" },
];
var newArr = rows.map(function(elem) {
return {
id: elem.id,
img: elem.img
};
});
console.log('newArr', newArr);
回答by Mihai Alexandru-Ionut
Just use mapmethod by passing a callbackfunction.
只需map通过传递callback函数来使用方法。
let rows = [ { id: 3, title: "sometitle", catid: 55, img: "file" }, { id: 4, title: "sometitle", catid: 55, img: "file" }, { id: 5, title: "sometitle", catid: 55, img: "file" }]
console.log(rows.map(function({id, img}){
return {id, img};
}));
or using arrowfunctions.
或使用arrow函数。
let rows = [ { id: 3, title: "sometitle", catid: 55, img: "file" }, { id: 4, title: "sometitle", catid: 55, img: "file" }, { id: 5, title: "sometitle", catid: 55, img: "file" }]
console.log(rows.map(({ id, img }) => ({ id, img })));
回答by Andy
回答by Ali Shawky
Use This Code :-
使用此代码:-
let rows = [
{ id: 3, title: "sometitle", catid: 55, img: "file" },
{ id: 4, title: "sometitle", catid: 55, img: "file" },
{ id: 5, title: "sometitle", catid: 55, img: "file" }]
let newRows = [];
rows.forEach(function(value,index){
let obj = {};
obj.id = value['id'],
obj.img = value['img']
newRows.push(obj);
});
回答by Sagiv b.g
Classic for Array.prototype.map
经典之作 Array.prototype.map
const rows = [{
id: 3,
title: "sometitle",
catid: 55,
img: "file"
},
{
id: 4,
title: "sometitle",
catid: 55,
img: "file"
},
{
id: 5,
title: "sometitle",
catid: 55,
img: "file"
},
];
const newArr = rows.map(({id,img}) => ({id,img}));
console.log(newArr);
回答by Mark Schultheiss
This is not really an answer, uses others answers:BUT: Just for fun I ran some rough tests on the presented solutions (I used a super old computer with Firefox, your results will likely vary.
这不是一个真正的答案,使用其他答案:但是:只是为了好玩,我对所提供的解决方案进行了一些粗略的测试(我使用了一台带有 Firefox 的超旧计算机,您的结果可能会有所不同。
Just for fun, to leverage StackOverflow I pulled from other questions :) added references to stuff.
只是为了好玩,为了利用我从其他问题中提取的 StackOverflow :) 添加了对东西的引用。
EDIT Added the accepted answer in test 8
编辑在测试 8 中添加了接受的答案
My results: RUN YOUR OWN TESTS, MULTIPLE TIMES results vary some
我的结果:运行您自己的测试,多次结果会有所不同
test0 forEach 78.75
test1 map arrow 82.6
test2 map function 78.85
test3 negative for compact 12.6
test4 for 13.3
test5 cached len for 61.55
test6 negative for long 10
test7 negative while 12.5
test8 map accepted 91.35 // the accepted answer, sometimes it is faster
Second execution: note how it changes **RUN YOUR OWN TESTS**
test0 forEach 155.95 // nearly always the looser
test1 map arrow 13.25
test2 map function 14.9
test3 negative for compact 7 // sometimes wins!
test4 for 18.7
test5 cached len for 7.8
test6 negative for long 61.65
test7 negative while 23.4
test8 map accepted 10.15 // odd it is fast sometimes, sometimes not
Before I added the last test: (so comments are relevant)
test name avg milliseconds on 100,000
test0 forEach 279.15
test1 map arrow 21.25
test2 map function 10.1
test3 negative for compact 22.6
test4 for 15.55
test5 cached len for 18.75
test6 negative for long 185.7
test7 negative while 35.05
// two executions 100 times instead of 20
/* test 100 times
test0 forEach 205.56
test1 map arrow 20.35
test2 map function 20.72
test3 negative for compact 27.07
test4 for 40.75
test5 cached len for 18.39
test6 negative for long 10.37
test7 negative while 12.93
test8 map accepted 9.53
100 times again
test0 forEach 151.19
test1 map arrow 18.22
test2 map function 40.27
test3 negative for compact 87.53
test4 for 48.18
test5 cached len for 17.14
test6 negative for long 14.06
test7 negative while 16.53
test8 map accepted 13.41
Excerpt of code :test2
`var newRows2 = rows.map(function({id,img}) {return {id,img};});`
My messy tests:
我凌乱的测试:
// create an array we can append to
const rows = [{
id: 3,
title: "sometitle",
catid: 55,
img: "file"
},
{
id: 4,
title: "sometitle",
catid: 55,
img: "file"
},
{
id: 5,
title: "sometitle",
catid: 55,
img: "file"
}
];
// hold some results
var testresult = [];
// add some objects to our array, bulk it up
for (var a = 0; a < 100000; a++) {
rows.push({
id: a,
title: "sometitle",
catid: a,
img: "file"
});
}
// go grab a group by from here: https://stackoverflow.com/a/38327540/125981
function groupBy6(list, keyGetter) {
const map = new Map();
list.forEach((item) => {
const key = keyGetter(item);
const collection = map.get(key);
if (!collection) {
map.set(key, [item]);
} else {
collection.push(item);
}
});
return map;
}
// just to make it simple, push in a result
function testResult(test, name, value1, value2) {
testresult.push({
test: test,
value: value2 - value1,
name: name
});
}
// go grab a sum function from here: https://stackoverflow.com/a/23249575/125981 (in the comments)
var sum = function(items, prop) {
if (items == null) {
return 0;
}
return items.reduce(function(a, b) {
return b[prop] == null ? a : a + b[prop];
}, 0);
};
// some super ugly tests :)
function test() {
// test
var t0 = performance.now();
newRows0 = [];
rows.forEach(function(value, index) {
let obj = {};
obj.id = value['id'];
obj.img = value['img'];
newRows0.push(obj);
});
var t1 = performance.now();
testResult("test0", "forEach", t0, t1);
var t2 = performance.now();
const newRows1 = rows.map(({
id,
img
}) => ({
id,
img
}));
var t3 = performance.now();
testResult("test1", "map arrow", t2, t3);
var t4 = performance.now();
var newRows2 = rows.map(function({
id,
img
}) {
return {
id,
img
};
});
var t5 = performance.now();
testResult("test2", "map function", t4, t5);
var t6 = performance.now();
newRows3 = [];
for (var i = rows.length; i--;) {
newRows3.push({
"id": rows[i]['id'],
"img": rows[i]['img']
});
}
var t7 = performance.now();
testResult("test3", "negative for compact", t6, t7);
var t8 = performance.now();
newRows4 = [];
for (var i = 0; i < rows.length; i++) {
newRows4.push({
"id": rows[i]['id'],
"img": rows[i]['img']
});
}
var t9 = performance.now();
testResult("test4", "for", t8, t9);
var t10 = performance.now();
newRows5 = [];
var len = rows.length;
for (var i = 0; i < len; i++) {
newRows5.push({
"id": rows[i]['id'],
"img": rows[i]['img']
});
}
var t11 = performance.now();
testResult("test5", "cached len for", t10, t11);
var t12 = performance.now();
newRows6 = [];
for (var i = rows.length - 1; i >= 0; i--) {
newRows6.push({
"id": rows[i]['id'],
"img": rows[i]['img']
});
}
var t13 = performance.now();
testResult("test6", "negative for long", t12, t13);
var t14 = performance.now();
newRows7 = [];
var i = rows.length;
while (i--) {
newRows7.push({
"id": rows[i]['id'],
"img": rows[i]['img']
});
}
var t15 = performance.now();
testResult("test7", "negative while", t14, t15);
var t16 = performance.now();
var test8 = rows.map(function(elem) {
return {
id: elem.id,
img: elem.img
};
});
var t17 = performance.now();
testResult("test8", "map accepted", t16, t17);
}
// run the test 20 times, not super great statistically speaking
for (var t = 0; t < 20; t++) {
test();
}
// get each group and sum them up in an ugly way
const groupeds = groupBy6(testresult, tst => tst.test);
var groupy = Array.from(groupeds);
groupy.forEach(function(entry) {
var s = sum(entry[1], "value");
var sn = +(s / entry[1].length).toFixed(2);
console.log(entry[0], entry[1][0].name, sn);
});
回答by Mohammad Noor
Well this isn't Java but where are the rows. You aren't making a line, your making an array so if you were making a line you might as well just do variables.
嗯,这不是 Java,而是行在哪里。你不是在做一条线,你在做一个数组,所以如果你在做一条线,你最好只做变量。
Try this
试试这个
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

