-1

I have an array of objects which looks like

arr = [
    {"className":"section", "name":"input"},
    {"className":"col", "name":"dropdown"},
    {"className":"section", "name":"table"}
] 

Now I want to push an object {"fieldName":"new"} after every object which has "className":"section"

So my final output should look like something like this

arr = [
    {"className":"section", "name":"input"},
    {"fieldName":"new"},
    {"className":"col","name":"dropdown"},
    {"className":"section", "name":"table"},
    {"fieldName":"new"}]

How do I acheive this in Javascript?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Yaditya
  • 47
  • 7
  • Do you have to push these into the same array? It's easier if you create a new array. – Barmar Jul 20 '21 at 05:45
  • There's no [JSON](https://www.json.org/json-en.html) in your question -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Jul 20 '21 at 05:46
  • What have you tried so far to solve this on your own? – Andreas Jul 20 '21 at 05:47

2 Answers2

0

Use Array.reduce.

let arr = [{"className":"section", "name":"input"},{"className":"col", "name":"dropdown"},{"className":"section", "name":"table"}];

arr = arr.reduce((acc, item) => {
    acc.push(item);
    if (item.className === "section") {
        acc.push({ fieldName: "new" });
    }
    return acc;
}, []);

console.log(arr);
Joel Rummel
  • 802
  • 5
  • 18
0

try this...

arr.forEach(obj => {
 if (obj.className === 'section') {
  const index = arr.indexOf(obj)
  arr.splice(index, 0, 
  {"fieldName":"new"} )
 }
})
Praveen Kumar
  • 49
  • 1
  • 6