最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript loop through array of objects and take two values and insert into new array of objects - Stack Overflow

programmeradmin10浏览0评论

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:

newArr [
{ id: 3,
 img: "file" },
{ id: 4,
 img: "file" },
{ id: 5,
 img: "file" },
]

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:

newArr [
{ id: 3,
 img: "file" },
{ id: 4,
 img: "file" },
{ id: 5,
 img: "file" },
]
Share Improve this question asked Feb 7, 2018 at 15:02 KiowKiow 8804 gold badges19 silver badges32 bronze badges 2
  • What have you tried? Please show your attempt so we may help fix it. Fix the syntax errors also so that you do show the effort you made. – Mark Schultheiss Commented Feb 7, 2018 at 15:03
  • 1 array.map(function(item) { return {id: item.id, img: item.img}}); – Pavel Staselun Commented Feb 7, 2018 at 15:05
Add a ment  | 

7 Answers 7

Reset to default 16

You can easily do this using 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);

Just use map method by passing a callback function.

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 arrow functions.

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 })));

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);
});

Classic for 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);

ES6 method using 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 out = rows.map(({ id, img }) => ({ id, img }));

console.log(out);

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 puter with Firefox, your results will likely vary.

Just for fun, to leverage StackOverflow I pulled from other questions :) added references to stuff.

EDIT Added the accepted answer in test 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 pact 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 pact 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 ments 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 pact 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 pact 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 pact 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./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./a/23249575/125981 (in the ments)
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 pact", 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);
});

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.

Try this

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论