dede.brahma
dede.brahma

Reputation: 329

how to push array value to another array object value javascript

I've data response like this

{
"data": {
  "product": {
    "colors": ["#3498db", "#00ccff"],
    "items": [
     {
       "label": "Phone",
       "value": "23.00"
     },
     {
       "label": "Notebook",
       "value": "3.00"
     }
    ]
   }
 }
}

and then i want push the colors inside items

expected: items have three(3) variable each of index

items: [
 {
  label: phone,
  value: 23.00,
  color: #3498db
 }
]

i've try using push and concat but i got error "Cannot read property 'data' of undefined"

here my code

generaliseData(dashboardC) {
  let genData = Object.assign({}, dashboardC)
    if (genData.product.items.length > 0) {
      for (let i of genData.product.items) {
        i.value = parseInt(i.value)
          for (let j of genData.product.colors) {
            i = i.push(j)
          }
       }
      console.log(genData)
    }
 }

Upvotes: 0

Views: 197

Answers (3)

Đào Minh Hạt
Đào Minh Hạt

Reputation: 2928

You can use map to iterate through your list, expect to have the length of colors equal the length of item

const response = {
"data": {
  "product": {
    "colors": ["#3498db", "#00ccff"],
    "items": [
     {
       "label": "Phone",
       "value": "23.00"
     },
     {
       "label": "Notebook",
       "value": "3.00"
     }
    ]
   }
 }
};
function addColorToItem(response) {
  const product = response.data.product;
  const colors = product.colors;
  const items = product.items;
  
  return items.map((item, index) => {
    item.color = colors[index];
    return item;
  })
}

console.log(addColorToItem(response));

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30729

You can use a simple forEach() loop for that result:

var data = {
  "product": {
    "colors": ["#3498db", "#00ccff"],
    "items": [{
        "label": "Phone",
        "value": "23.00"
      },
      {
        "label": "Notebook",
        "value": "3.00"
      }
    ]
  }
};
data.product.items.forEach((item, index) => item.color = data.product.colors[index]);
console.log(data);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386868

You could iterate items and assign a color.

var response = { data: { product: { colors: ["#3498db", "#00ccff"], items: [{ label: "Phone", value: "23.00" }, { label: "Notebook", value: "3.00" }] } } },
    temp = response.data.product;

temp.items.forEach((o, i) => o.color = temp.colors[i]);

console.log(response);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

Related Questions