Javascript: Map in for loop always return last item

I am attempting to modify an array of objects and I use a map inside a for loop. My implementation always seem to return the last item in the map.

Code:

let testArray = [
    {
        body: 'test sentence',
        uid: "a"
    },
    {
        body: 'Another test sentence',
        uid: "b"
    }
]

var allItems = []
for (var item of testArray) {
    let splittedBody = item.body.split(' ')

    let splittedArray = splittedBody.map((word, i) => {
        item.body = word
        item.objectID = `${item.uid}:${i}`
        return item
    })
    allItems.push(splittedArray)
}

allItems = Array.prototype.concat(...allItems)
console.log(allItems)

The above code prints the following:

[ { body: 'sentence', uid: 'a', objectID: 'a:1' },
  { body: 'sentence', uid: 'a', objectID: 'a:1' },
  { body: 'sentence', uid: 'b', objectID: 'b:2' },
  { body: 'sentence', uid: 'b', objectID: 'b:2' },
  { body: 'sentence', uid: 'b', objectID: 'b:2' } ]

What I want is:

[ { body: 'test', uid: 'a', objectID: 'a:0' },
  { body: 'sentence', uid: 'a', objectID: 'a:1' },
  { body: 'Another', uid: 'b', objectID: 'b:0' },
  { body: 'test', uid: 'b', objectID: 'b:1' },
  { body: 'sentence', uid: 'b', objectID: 'b:2' } ]

EDIT: Ideally, I would not like to construct another item in my map function because each object in the testArray may have attributes that do not exist in other object. Constructing another item in the map function would mean that I have to check for undefined in those attributes and this is very prone to errors.

Your problem here come from the shadowing that you do with item:

let testArray = [{
    body: 'test sentence',
    uid: "a"
  },
  {
    body: 'Another test sentence',
    uid: "b"
  }
]

var allItems = []
for (var item of testArray) {
  let splittedBody = item.body.split(' ')

  let splittedArray = splittedBody.map((word, i) => {

    // Create a clone of item -> don't use item
    var itemClone = JSON.parse(JSON.stringify(item)); 
    
    itemClone.body = word
    itemClone.objectID = `${item.uid}:${i}`
    return itemClone       // <-- return the modified clone
  })
  allItems.push(splittedArray)
}

allItems = Array.prototype.concat(...allItems)
console.log(allItems)

Javascript get last item in array Code Example, Get code examples like "Javascript get last item in array" instantly right from your google search results with the Grepper Chrome Extension. If you’re starting in JavaScript, maybe you haven’t heard of .map(), .reduce(), and .filter().For me, it took a while as I had to support Internet Explorer 8 until a couple years ago.

When you set item.body, it mutates the original object. And you need more objects than the length of the testArray since you create new objects by splitting.

Update:

Since you want existing properties of item to remain, you can use spread operator as following:

let testArray = [{
    body: "test sentence",
    uid: "a",
    foo: 'foo'
  },
  {
    body: "Another test sentence",
    uid: "b",
    bar: 'bar'
  }
];

var allItems = []
for (var item of testArray) {
  allItems.push(
    item.body.split(' ').map((word, i) => ({
        ...item,
//    ^^^^^^^ Here you can use spread operator to merge newly created object with the item

        body: word,
        objectID: `${item.uid}:${i}`
      })
    )
  )
}

allItems = Array.prototype.concat(...allItems)
console.log(allItems)

Get the first and last item in an array using JavaScript, Javascript array is a variable which holds multiple values at a time. The first and last elements are accessed using an index and the first value is� For-of loop is a great ES2015+ feature (handled by all browsers but IE…) that allows us to iterate over the values of an array in JavaScript. The only native way to achieve that before this new…

You can make it like this simple.

let testArray = [
{
    body: 'test sentence',
    uid: "a"
},
{
    body: 'Another test sentence',
    uid: "b"
}
]
var allItems = [];
    for (var item of testArray) {
      let splittedBody = item.body.split(' ')
      splittedBody.map((word, i) => {
        let item1: any = {};
        item1.body = word;
        item1.uid = item.uid;
        item1.objectID = `${item.uid}:${i}`;
        allItems.push(item1);
      });
    }
    allItems = Array.prototype.concat(...allItems);
    console.log(allItems);

How to check if an element of an array is the last within a loop in , To check wheter an iteration is the last in the loop or not, we only need because as everybody knows, the first element of the array is always 0� If you use await in a map, map will always return an array of promises. This is because asynchronous functions always return promises. const mapLoop = async _ => { console.log('Start') const numFruits = await fruitsToGet.map(async fruit => { const numFruit = await getNumFruit(fruit) return numFruit }) console.log(numFruits) console.log('End') }

The Essential Guide to JavaScript Map: How To Use Maps Effectively, This tutorial introduces you to the JavaScript Map object and shows you how to An object always has a default key like the prototype. It returns the map object itself therefore you can chain this method with other Iterate over map keys. JavaScript does this because forEach is not promise-aware. It cannot support async and await. You _cannot_ use await in forEach. Await with map. If you use await in a map, map will always return an array of promise. This is because asynchronous functions always return promises.

Array.prototype.lastIndexOf(), The lastIndexOf() method returns the last index at which a given element can be The last index of the element in the array; -1 if not found. My point is that the Reduce Method In JavaScript gives you a mini CodePen where you can write whatever logic you want. It will repeat the logic for each amount in the array and then return a single value. The thing is, you don’t always have to return a single value. You can reduce an array into a new array.

array_key_last - Manual, Get the last key of the given array without affecting the internal array pointer. Parameters �. array. An array. Return Values �. Returns the last key of array if the array is not empty; NULL otherwise. var_dump(_array_key_last(['PHP', ' Javascript', 'Python'])); // 2 ?> Use-cases include lots of looping and control- structures. Primitive wrapper types – learn how primitive wrapper types work in JavaScript. Section 9. Advanced Functions. Passing by value – understand how pass-by-value works in JavaScript. Returning multiple values – guide you on how to return multiple values from a function. Function type – introduce you to the Function type and its properties

Comments
  • What is the question?
  • I don't think you want to do item.body = word, that will overwrite the original sentence.
  • Create a var item = {} inside the map
  • You don't want to set item in your inner loop, which is your outer loop's iteration variable. Just build a new object in your map function: jsfiddle.net/khrismuc/x42qjwvc
  • I updated my answer to accomplish what you want in your edit section. Please have a look at it.
  • Ideally, I do not want to construct a new item to append to allItems because each object in the json can have differing attributes. Each object has up to 10 attributes and constructing a new item means that I have to check for undefined in all the differing attributes. Is there a way to do so?
  • @Koh Yes you can do that using a clone of the initial item. Take a look at this question for more details. I updated my example.