Home > Blockchain >  How to copy a variable arrray from another arrray in javascripts
How to copy a variable arrray from another arrray in javascripts

Time:10-28

I have an array as below:

 const arr = [
        {
            title: 's4',
            value: '124'
        },
        {
            title: 's2',
            value: '121'
        },
        {
            title: 's3',
            value: '122'
        }
    ];

and I want to create a new another array copy from the old array same as below:

 const arrCopy = [
        {
            value: '124'
        },
        {
            value: '121'
        },
        {
            value: '122'
        }
    ];

then my code as below:

var arrCopy = [...arr,arr.value]

but it has a problem, so anyone help me, thanks.

CodePudding user response:

you can use Array.prototype.map()

 const arr = [
        {
            title: 's4',
            value: '124'
        },
        {
            title: 's2',
            value: '121'
        },
        {
            title: 's3',
            value: '122'
        }
    ];
    
    
const newArr = arr.map((element) => {
    return {
    value: element.value
  }
})

console.log(newArr)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

can even shorten the above expression to one line

const newArr = arr.map(element => ({value: element.value}))

CodePudding user response:

Just as in the comment above you can use awesome Javascript functions, in this case, you would like to use the map function of your array to map every item of the array as you like.

const arrayMapped = yourArray.map(item => {
    value: item.value
  })

Here is another way using Javascript Destructuring, you just ask with properties would you like from the JS Object, in this case, you just like the value property.

  const arrayMapped = yourArray.map(( { value } ) => ( { value } ))

How Array.map works How Object Destructuring works

CodePudding user response:

You can simply use Array.map, as it returns a new array with the required value.

const newArr = arr.map(element => ({ value: element.value }))
console.log(newArr);

For references : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

  • Related