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

JavaScript: Add new attribute to object in an array - Stack Overflow

programmeradmin4浏览0评论

I am trying to add an item into an existing object in an array (index each array):

const dataInput = [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
]

This is what I've tried:

dataInput.map((data, index) => {
  availableItems.push({'idx':index})
})

This pushes a new object instead of adding the element to the existing first and second.

[
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
  {idx:0},
  {idx:1}
]

How could I achieve that? (below is what I need)

[
  { title: 'first', description: 'test 1', idx: 0 },
  { title: 'second', description: 'test 1', idx:1 },
]

I am trying to add an item into an existing object in an array (index each array):

const dataInput = [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
]

This is what I've tried:

dataInput.map((data, index) => {
  availableItems.push({'idx':index})
})

This pushes a new object instead of adding the element to the existing first and second.

[
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
  {idx:0},
  {idx:1}
]

How could I achieve that? (below is what I need)

[
  { title: 'first', description: 'test 1', idx: 0 },
  { title: 'second', description: 'test 1', idx:1 },
]
Share Improve this question edited Dec 27, 2020 at 14:09 ayaz 228 bronze badges asked Dec 27, 2020 at 12:34 Alex BranAlex Bran 4631 gold badge8 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You need to add a new attribute at each iteration:

const dataInput = [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
];

const res = dataInput.map( (data, index) => ({...data, idx:index}) );

console.log(res);

Another option:

dataInput.forEach((element, index) => (element["idx"] = index));

Another option:

const dataInput= [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
]

const result = dataInput.reduce((acc, cur, index) => {
    acc.push({...cur, idx: index})
    return acc
},[])

console.log(result)

发布评论

评论列表(0)

  1. 暂无评论