how to get array according to conditions in javascript

Viewed 42

My array comes like this

var data=[{PRODUCT : P1}, {PRODUCT: P2}]

I wantt to convert this into [P1, P2]. Sometimes my array comes like this

var data=[{ITEM: I1, QUANTITY:1}, {ITEM: I2, QUANTITY:2}]

I wantt to convert this into [I1, I2].

so can we make a common function, where I just want to extract particular value of array and make a new array. p.s. Thank you in advance


I tried to write the logic like this:

data.map((d, index) => { var result= [];
               result.includes(d[0]); })

but it,s not dynamic

3 Answers

You could define a function which will always get the first value of the first object key, this should satisfy your needs based on the above

var data1 = [{
  ITEM: 'I1',
  QUANTITY: 1
}, {
  ITEM: 'I2',
  QUANTITY: 2
}]

var data2 = [{
  PRODUCT: 'P1'
}, {
  PRODUCT: ' P2'
}]

function getArrayOfValues(list) {
  return list.reduce((acc, x) => {
    const firstValue = Object.values(x)[0];
    acc.push(firstValue)
    return acc;
  }, [])
}

const result1 = getArrayOfValues(data1)
console.log(result1)

const result2 = getArrayOfValues(data2)
console.log(result2)

function getProductOrItem(list) {
      return list.reduce((accumulator, obj) => {
        if (obj.PRODUCT) {
            accumulator.push(obj.PRODUCT);
        } else if (obj.ITEM) {
            accumulator.push(obj.ITEM);
        }
        return accumulator;
      }, [])
    }

you can iterate through your array with map() method and inside it extract the value of a first entity of an object in your array and simply get a new array with all values:

const data1 =[{PRODUCT : 'P1'}, {PRODUCT: 'P2'}]
const data2 = [{ITEM: 'I1', QUANTITY: 1}, {ITEM: 'I2', QUANTITY: 2 }]
const transformValuesOfArray = (arrayToTransform) => 
arrayToTransform.map(value => {
 const firstObjectValue = Object.values(value)[0]
 return firstObjectValue
})
console.log(transformValuesOfArray(data1))
console.log(transformValuesOfArray(data2))

Related