skip to Main Content

I try to convert current array to expected array using some code , but it was not working. I tried react/ javacript

Currernt Array 
[
{"name" : "john" ,"values" :["first","second","third","four"]},
{"name" : "sachin" ,"values" :["five","six","seven","eight"]},
]


Expected Array 
[
{"name" : "john","a" : "first", "b" :"second", "c":"third", "d" : "four"},
{"name" : "sachin","a" : "five", "b" :"six", "c":"seven", "d" : "eight"} 
]




const newArrayOfObj =  this.state.data.map(({
      values[0]: a,
      values[1]: b,
      values[2]: c,
      values[3]: d,
      ....
    }) => ({
      a, b, c, d,
      ....
    }));

5

Answers


  1. I wrote a quick one here. Check if it could meet your need

    const array = [
      { "name": "john", "values": ["first", "second", "third", "four"] },
      { "name": "sachin", "values": ["five", "six", "seven", "eight"] },
    ];
    
    const keys = "abcdefghijklmnopqrstuvwxyz";
    const newArray = array.map(({name, values}) => {
      const newValueList = values.map((value, i) => ({ [keys[i]]: value }));
      return Object.assign({ name }, ...newValueList);
    })
    
    console.log(newArray)
    Login or Signup to reply.
  2. You can try with this snippet

    ``
    const inputArr = [
      { "name": "john", "values": ["first", "second", "third", "four"] },
      { "name": "sachin", "values": ["five", "six", "seven", "eight"] },
    ];
    
    const outputArr = inputArr.map((item) => {
      const newItem = { "name": item.name };
      item.values.forEach((value, index) => {
        newItem[String.fromCharCode(97 + index)] = value;
      });
      return newItem;
    });
    
    console.log(outputArr);
    Login or Signup to reply.
  3. Here is a proposal

    const data = [{
      "name": "john",
      "values": ["first", "second", "third", "four"]
    }, {
      "name": "sachin",
      "values": ["five", "six", "seven", "eight"]
    }, ];
    
    const out = data.map(o => {
      return {
        name: o.name,
        ...["a", "b", "c", "d"].reduce((vals, key, i) => {
          vals[key] = o.values[i];
          return vals
        }, {})
      }
    });
    
    console.log(out)
    Login or Signup to reply.
  4. Use two nested reducers. The first passes over the outer array of object, the second passes over the values.

    I ran it in TDD style:

    const test = () => {
    
      it('transform array with array to enumerated object', () => {
    
        const keys = ['a', 'b', 'c', 'd']
    
        function valueReducer(acc, v, i) {
          acc[keys[i]] = v
          return acc
        }
    
        function arrayReducer(acc, obj) {
          const valuesObj = obj.values.reduce(valueReducer, {})
          const newObj = {
            name: obj.name,
            ...valuesObj
          }
          acc.push(newObj)
          return acc
        }
    
        const transformed = current.reduce(arrayReducer, [])
       
        expect(transformed).to.deep.eq(expected) // passes
      })
    
    };
    
    describe('Array Transformation', test);
    mocha.run();
    <!-- Mocha CSS for styling the test results -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/mocha/mocha.css">
    <!-- Mocha JS library -->
    <script src="https://cdn.jsdelivr.net/npm/mocha/mocha.js"></script>
    <!-- Chai JS library -->
    <script src="https://cdn.jsdelivr.net/npm/chai/chai.js"></script>
    <div id="mocha"></div>
    
    
    <script>
    
    document.addEventListener("click", (e) => {
      if (e.target.matches(".replay")) e.preventDefault()
    })
    
    mocha.setup('bdd'); // bdd is for behavior-driven development
    
    const {
      expect
    } = chai;
    
      const current = [
        {"name" : "john" ,"values" :["first","second","third","four"]},
        {"name" : "sachin" ,"values" :["five","six","seven","eight"]},
      ]
      const expected =  [
        {"name" : "john","a" : "first", "b" :"second", "c":"third", "d" : "four"},
        {"name" : "sachin","a" : "five", "b" :"six", "c":"seven", "d" : "eight"} 
      ]
    
    </script>
    Login or Signup to reply.
  5. An one-liner:

    const inputArr = [
      { "name": "john", "values": ["first", "second", "third", "four"] },
      { "name": "sachin", "values": ["five", "six", "seven", "eight"] },
    ];
    
    const outputArr = inputArr.map(({name, values}) => ({name, ...values.reduce((r, e, i) => (r[String.fromCharCode(97 + i)] = e, r), {})}));
    
    console.log(outputArr);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search