0

This is my array

const arr = [
{ id: "1", hello: "hello1" },
{ id: "2", hello: "hello2" },

];

I want this code

const finalarr = [
{ id: "1", hello: "hello1", bye: 'bye1' },
{ id: "2", hello: "hello2", bye: 'bye2' },

];

3
  • What have you tried, and what exactly is the problem with it? Do you know how to add a prop to an object? How to loop over an array? Commented May 9, 2020 at 14:37
  • thanks jonrsharpe I created this for object but I don't understand how to create for an array var addToObject = function (obj, key, value, index) { var temp = {}; var i = 0; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { // If the indexes match, add the new item if (i === index && key && value) { temp[key] = value; } // Add the current item in the loop to the temp obj temp[prop] = obj[prop]; // Increase the count i++; } } if (!index && key) { temp[key] = value; } return temp; }; Commented May 9, 2020 at 14:49
  • Then edit to give a minimal reproducible example. Commented May 9, 2020 at 14:51

2 Answers 2

1

Try with map:

var arr = [{ id: "1", hello: "hello1" },{ id: "2", hello: "hello2" }];
result = arr.map(elem=>({...elem, 'bye':`bye${elem.id}`})); // with attaching the id
result2 = arr.map((elem,i)=>({...elem, 'bye':`bye${i+1}`})); // by generating id;
console.log(result);
console.log(result2);

Sign up to request clarification or add additional context in comments.

Comments

0

By using the below loop in your code you can get ur required output.

  for (var i =0;i<arr.length;i++){
    arr[i]["bye"] = "bye"+(i+1); 
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.