1

I have json object with following structure:

$scope.sellAccessories[0]=[
{id: [178], item_name: ["Nescafe","ggfftrww"], quantity: [1], total_price:[300]}
]

my problem is that i want to remove some elements from the array before i send the json object to the server side.

i tried to remove the second element in the array item_name which is ggfftrww using the splice function:

var index = $scope.sellAccessories[0].item_name.indexOf($scope.sellAccessories[0].item_name[1]);

if (index > -1) {
   $scope.sellAccessories[0].item_name.splice(index, 1);
}

but it didn't work.

thanks in advance this is stopping my work flow.

3 Answers 3

1

Its better to bring out your item_name to a variable, perform the splice and then set the result to the object property as follows;

var itemToChange=$scope.sellAccessories[0].item_name;
var index = itemToChange.indexOf(itemToChange[1]);

if (index > -1) {
   itemToChange.splice(index, 1);
   $scope.sellAccessories[0].item_name=itemToChange;
}
Sign up to request clarification or add additional context in comments.

2 Comments

this is easy and nice!
splice mutates the original array; the last line there is redundant.
1

JSON is a method of formatting a string; if what you're dealing with isn't a string, call it an object or array.

From your question, sellAccessories is an array of arrays - it's not just a plain array, so you can't just access the item_name through sellAccessories[0].item_name.

Objects are only references to memory locations, so you can simply access the array and remove the appropriate property:

const scope = { sellAccessories: [] };
scope.sellAccessories[0] = [{
  id: [178],
  item_name: ["Nescafe", "ggfftrww"],
  quantity: [1],
  total_price: [300]
}]
const { item_name } = scope.sellAccessories[0][0];
item_name.splice(item_name.indexOf('ggfftrww'));
console.log(item_name);

Comments

1

Instead of doing with multiple steps, you could do it with single line as mentioned below.

$scope.sellAccessories[0] = $scope.sellAccessories[0]['item_name'].splice(0,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.