Key-Value Pair Json transformation and conversion into a class in Javascript / Jquery

Below is the structure of my JSON in Javascript

[
    [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
    [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
    [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
]

I want to transform this in Javascript / Jquery by removing "key" and "value" and make it

[
    {"firstname" : "David", "lastname" : "Smith"},
    {"firstname" : "Allen", "lastname" : "Grover"},
    {"firstname" : "Randy", "lastname" : "Paul"}
]

And in addition am also looking to see if I can convert this json into javascript array of objects where I can access the properties like below would be great.

var people =[];

people[0].firstname = "David";
people[1].lastname = "Smith";

Upvotes: 0

Views: 266

Answers (6)

Mark
Mark

Reputation: 92440

It makes a pretty nice functional one-liner:

let arr = [[{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],[{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],[{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]]

let o = arr.map(item => item
        .reduce((a, {key, Value}) => ({[key]: Value, ...a} ), {}))

console.log(o)

Upvotes: 1

Blue
Blue

Reputation: 22911

You can use .map() and .reduce() to achieve this functionality:

var arr = [
    [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
    [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
    [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
];

var final = arr.map(keys => {
  // Build the object, by attaching each key to the value
  return keys.reduce((obj, key) => {
    obj[key.key] = key.Value;
    return obj;
  }, {});
});
console.log(final);

Now, onto your question about handlebars/react/html framework. Here is an example of how you can do this dirt simple in react:

var arr = [
    [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
    [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
    [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
];

var final = arr.map(keys => {
  // Build the object, by attaching each key to the value
  return keys.reduce((obj, key) => {
    obj[key.key] = key.Value;
    return obj;
  }, {});
});

class App extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      data: props.data
    };
  }
  
  render() {
    return React.createElement('div', null,
      this.state.data.map(name =>
        React.createElement('div', null,
          `Name: ${name.firstname} ${name.lastname}`
        )
      )
    );
  }
}

ReactDOM.render(React.createElement(App, {data: final}), document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Note: This code is rather ugly, as I have to resort to using React.createElement, something of which is not required when using JSX.

Upvotes: 3

Rohit.007
Rohit.007

Reputation: 3502

You can do it by map

var arrList = [
    [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
    [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
    [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
];

var readyResult = arrList.map(start => {
  resultSet = {};
  start.forEach(obj => {
    resultSet[obj.key] = obj.Value;
  });
  return resultSet;
});

console.log(readyResult);

Upvotes: 0

dhilt
dhilt

Reputation: 20744

Just map your initial data array:

const data = [
  [{"key": "firstname", "Value": "David"}, {"key": "lastname", "Value": "Smith"} ],
  [{"key": "firstname", "Value": "Allen"}, {"key": "lastname", "Value": "Grover"} ],
  [{"key": "firstname", "Value": "Randy"}, {"key": "lastname", "Value": "Paul"} ]
];

const result = data.map(item => ({
  [item[0]['key']]: item[0]['Value'],
  [item[1]['key']]: item[1]['Value']
}));

console.log(result);

If the number of person objects per each data item could be > 2 then you need to update procedure, @FrankerZ answer is fine in that case. But if not, I would use explicit approach (without additional reducing) as more performant.

Upvotes: 1

Nishant Dixit
Nishant Dixit

Reputation: 5522

var data = [
    [{
        "key": "firstname",
        "Value": "David"
    }, {
        "key": "lastname",
        "Value": "Smith"
    }],

    [{
        "key": "firstname",
        "Value": "Allen"
    }, {
        "key": "lastname",
        "Value": "Grover"
    }],

    [{
        "key": "firstname",
        "Value": "Randy"
    }, {
        "key": "lastname",
        "Value": "Paul"
    }]
];

var result = data.map(v1 => {
    var vtemp = v1.map(v2 => ({
        [Object.values(v2)[0]]: Object.values(v2)[1]
    }))
    return { ...vtemp[0],
        ...vtemp[1]
    }
})

console.log(result);

console.log(result[0].firstname);

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

I'll do it as:

const ary = [
  [
    {
      key: "firstname",
      Value: "David"
    },
    {
      key: "lastname",
      Value: "Smith"
    }
  ],
  [
    {
      key: "firstname",
      Value: "Allen"
    },
    {
      key: "lastname",
      Value: "Grover"
    }
  ],
  [
    {
      key: "firstname",
      Value: "Randy"
    },
    {
      key: "lastname",
      Value: "Paul"
    }
  ]
];

let finalResult = ary.map(entry => {
  const result = {};
  entry.forEach(obj => {
    result[obj.key] = obj.Value;
  });
  return result;
});

console.log(JSON.stringify(finalResult, null, 2));
// [
//   {
//     "firstname": "David",
//     "lastname": "Smith"
//   },
//   {
//     "firstname": "Allen",
//     "lastname": "Grover"
//   },
//   {
//     "firstname": "Randy",
//     "lastname": "Paul"
//   }
// ] 

Upvotes: 0

Related Questions