0

I have JSON looks like this:

{
"ArrayInfo": [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
]
}

I want to replace an object of JSON with another object.For example I have this object :

{"name":"E","Id":"5"}

and it is going to be replaced by this object of JSON:

{"name":"B","Id":"2"}

JSON should look like this :

{
"ArrayInfo": [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "E",
        "Id": "5"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
]
}

What I did is to use Object.assign but the new object will be added to array instead of replacing. (all the data is going to be dynamic but for making more understandable I use static data)

const itemToReplace = { "name": "E", "Id": "5" };
const prevItem = ArrayInfo[2]
ArrayInfo = ArrayInfo.map((el, idx) => {
  return Object.assign({}, el, { prevItem: itemToReplace });
});
let NewArryInfo = ArrayInfo
console.log(NewArryInfo)

The result of console.log(NewArryInfo) :

{
"ArrayInfo": [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
    {
        "name": "E",
        "Id": "5"
    }
]
}
Sahar
  • 109
  • 2
  • 8
  • 2
    Your question does not seem related to react but raw javascript. You might want to change your title and tag to get more answers. – Kev Oct 18 '19 at 09:24
  • 2
    [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). Is it a JSON formatted string or a JavaScript object! – phuzi Oct 18 '19 at 09:29
  • ´Object.assign´ works that way, you can read here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign You can use ´splice´ instead. – Kote Oct 18 '19 at 09:31
  • It is a JSON Object. – Sahar Oct 18 '19 at 09:36
  • Either it is [JSON or an Object Literal](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation), "JSON Object" is not a thing. – str Oct 18 '19 at 09:42

5 Answers5

2

You can use Array.prototype.splice to replace an item in Array.

const replaceItem = {"name":"E","Id":"5"}
const ArrayInfo = [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
];
ArrayInfo.splice(1, 1, replaceItem); // remove second item and replace
console.log(ArrayInfo);
Diamond
  • 3,470
  • 2
  • 19
  • 39
  • Thanks @Antonio for your answer. Could you please explain what are the numbers splice(**1**, **1** .. in splice mean? – Sahar Oct 18 '19 at 09:33
  • First `1` is for second item, and second `1` is the number of items to be deleted, :) – Diamond Oct 18 '19 at 09:39
  • @Maya Read the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). – str Oct 18 '19 at 09:41
1

const object = {
  "ArrayInfo": [{
      "name": "A",
      "Id": "1"
    },
    {
      "name": "B",
      "Id": "2"
    },
    {
      "name": "C",
      "Id": "3"
    },
    {
      "name": "D",
      "Id": "4"
    }
  ]
};

const objectToReplace = {
  "name": "B",
  "Id": "2"
};

const updatedObject = Object.assign({}, object, {
  ArrayInfo: object.ArrayInfo.map((info) => {
    if (info.Id === objectToReplace.Id && info.name === objectToReplace.name) {
      return {
        "name": "E",
        "Id": "5"
      };
    }

    return info;

  })
});

console.log(updatedObject);
Umair Sarfraz
  • 5,284
  • 4
  • 22
  • 38
0

const myArr = [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
];


const replaceObj = (arr, objReplaced, objToReplaceWith) => {
  const replacedObjIndex = arr.findIndex(item => JSON.stringify(item) === JSON.stringify(objReplaced));
 arr[replacedObjIndex] = objToReplaceWith;
 console.log(arr)
 return arr;
}

replaceObj(myArr, {"name":"B","Id":"2"}, {"name":"E","Id":"5"});

In this way you can replace any object, from any position in the array. You won't have to worry about the position of the item that you want to replace in the array and also you won't need to worry about it's keys or values.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
0

Try this!

let ArrayInfo = [{"name": "A","Id": "1"},{"name": "B","Id": "2"},{"name": "C","Id": "3"},{"name": "D","Id": "4"}];
const onReplace = {"name":"E","Id":"5"};
const toReplace = {"name": "B","Id": "2"};

function replaceArray(array, onReplace, toReplace) {
  const removeIndex = array.map(item => { return item.name; }).indexOf(toReplace.name);
  array.splice(removeIndex, removeIndex, onReplace);
  return array
}

console.log(replaceArray(ArrayInfo, onReplace, toReplace));
Yahiya
  • 761
  • 4
  • 15
0

When you map over the array you could check if each item is the one you want to replace, and if it is, return the new item instead.

ArrayInfo = ArrayInfo.map((el, idx) => {
  if (el.id === prevItem.id && el.name === prevItem.name) {
    return itemToReplace;
  }
  return el;
});