0

I've array

var getData = [
  {
    "value": "20,
    "id": 2
  },
  {
    "value": "30",
    "id": 4
  },
  {
    "value": "40",
    "id": 6
  },
]

And I've data for example I want to check if product_id =2 I want to push ['product_id': 'thisistest'] into getData id = 2 the output will look like this

var getData = [
  {
    "value": "20,
    "id": 2,
    "product_id": "thisistest"
  },
  {
    "value": "30",
    "id": 4
  },
  {
    "value": "40",
    "id": 6
  },
]

Here is what I've try

for(let i in getData){
  const data = getData[i];
  //product_id ==2 
  if(data.id == product_id) {
    getData.push({
      //how can I push data into getData where id = 2
    });
  }
}
3
  • 1
    You have broken object literal not closing quote in first id "value": "20, it should be "value": "20",, your code will never run, you should have error in console. Commented Apr 24, 2019 at 10:39
  • 1
    data['product_id'] = 'thisistest'; (inside your if condition) is just enough instead of that getData.push, since those items are objects, not arrays. Of course, as long as product_id is 2. Commented Apr 24, 2019 at 10:40
  • thanks to all advice and comment Commented Apr 24, 2019 at 10:47

3 Answers 3

3

You can use map as well:

var getData = [
    {
        "value": "20",
        "id": 2
    },
    {
        "value": "30",
        "id": 4
    },
    {
        "value": "40",
        "id": 6
    },
]

var product_id = 4
var res = getData.map(x => x.id === product_id 
    ? ({...x, product_id: "thisistest"}) : x)

console.log(res)

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

2 Comments

Hi ,It's working Thank you. I know some people asking this kind of question but I'm new but still don't know about keyword to search it. I'm very appreciate to your answer. I'll mark green
@TryHard No need for apologizing, that's why SO is here :-) You can accept the answer then.
1

You can try map()

Please Note: You are missing closing " in "value": "20 which makes the object invalid.

var getData = [
    {
        "value": "20",
        "id": 2
    },
    {
        "value": "30",
        "id": 4
    },
    {
        "value": "40",
        "id": 6
    }
]

getData = getData.map(item => {
  if(item.id == 2)
    item["product_id"] = "thisistest";
  return item;
});

console.log(getData);

1 Comment

thanks, your answer is working too but I feel very sorry I've to mark the first answer .I'm very appreciated
0

try with this:

const change = (srchID, newKey, newValue) =>
getData.map(res => {
    if (res['id'] === srchID) {
        res[newKey] = newValue
    }
    return res
})

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.