change JSON structure using javascript - javascript

This is my code..
var result = data.map(function(item){
return {
category:item.category,
key:item.key,
value:item.value
}
});
console.log(result);
This is what is getting printed out in console..
Array[4]
0: Object
category: "common"
key: "Food"
value: "food"
1: Object
category: "welcome"
key: "title"
value: "Welcome..."
2: Object
category: "welcome"
key: "app_description"
value: "In this App "
3: Object
category: "welcome"
key: "select_location"
value: "Select Location"
This is what I'm trying to achieve
{
common:{
"Food" : "food"
},
welcome:{
title : Welcome...,
app_description : "In this App",
select_location : "Select Location"
}
}
This is the code I'm trying .but it is not working..
return {
item.category:{
item.key:item.value;
}
Can anyone help me with this? I dont want to use GSON or any other third-party JS..How can i get this done using only core JS?

First of all, what you want as a result is an object, not an array. So you can't use .map() which only maps one array to another array.
You want .reduce().
var result = data.reduce(function (result, item) {
// Create the object the first time it arrives
result[item.category] = result[item.category] || {};
// Add the field
result[item.category][item.key]=item.value;
// Return the resulting object
return result;
}, {});
console.log(result);
.reduce()'s reduction function takes two (with 2 more optional) parameters. The cumulative result, and the current item. The returned value is the result after the current item has been processed on it.
The second parameter for .reduce() (the first being the reduction function), is the initial value, this value will get passed as result for the first iteration.

Array.prototype.reduce() comes to rescue.
var result = data.reduce(function (previousValue, currentValue) {
previousValue[currentValue.category] = previousValue[currentValue.category] || {};
previousValue[currentValue.category][currentValue.key] = currentValue.value;
return previousValue;
}, {});

you can also try:
var data = [
{
category: "common",
key: "Food",
value: "food"
},
{
category: "welcome",
key: "title",
value: "Welcome..."
},
{
category: "welcome",
key: "app_description",
value: "In this App "
},
{
category: "welcome",
key: "select_location",
value: "Select Location"
}
];
var obj = {};
for (var i in data) {
if(!obj[data[i].category]){
obj[data[i].category] = {};
}
obj[data[i].category][data[i].key] = data[i].value;
}
console.log(obj);

Related

how to get only one value from array data and convert it into comma separted values. using javascript without template literals

i have array data in the format given below
const data= [
{
name: "productname",
id: "1356",
price: "0.00",
category: "Health",
position: "1",
list: "New Products",
stocklevel: "20",
brand: "Health"
},
{
name: "productname2",
id: "5263",
price: "0",
category: "Hair",
position: "2",
list: "New Products",
stocklevel: "",
brand: "Hair"
}]
from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-
product1name: "productname",
product2name: "productname2",
...
i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried
var dataByComa = '';
var Values = data
.map(function (p, i) {
return Object.keys(data[i]).map(function (k) {
return "prod" +" " + ": " + JSON.stringify(data[i][k]);
});
}).map(function (v) {
return v.join(",\n"); });
var commaValues = Values.join(",\n");
return commaValues;
with this code i can able to convert array data into comma separated values but i want only productnames.
Note :- Without using template template literals.
Edit: I'm more clear on what the OP was looking for now - here is an answer that fulfills all the requirements
let commaValues = ""
for (let i = 0; i < data.length; i++) {
commaValues += ("product" + (i + 1) + "name: " + "\"" + data[i]["name"] + "\", ")
}
// result: 'product1name: "productname", product2name: "productname2", '
You can do that using reduce. It takes a function as first and an initial value as second parameter (here an empty object {}).
The variable "previous" keeps track of the current state of the (initially empty) new object while the function adds the name of every single Element from the "data" array to the object.
var result = data.reduce((previous, element) => {
previous[element.name] = element.name;
return previous;
}, {})
EDIT:
As i realized, you actually want a string as result. In that case you could do:
var result = data.reduce((previous, element) => {
previous[element.name] = element.name;
return previous;
}, {})
var csvWithBrackets = JSON.stringify(result)
var csv = csvWithBrackets.substring(1, csvWithBrackets.length-1)
However the answer from Pzutils seems more compact.
You can iterate through the data and assign the value to an external variable like this:
let finalData = {}
data.forEach((item, index) => {
finalData[`product${index+1}name`] = item.name
})

Using ES6 Syntax to Map an Array of Values to Array of Truncated Objects

I am trying to use .map() and ES6 syntax to return a truncated version of each object in my array. I can do this to get one value from the original object passed on:
return dbJobs.map(job =>
job.data.modType
);
But how would I use ES6 syntax to handle taking an array of objects where each object looks like this:
{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}
... and return an array of objects where each object has two properties from the original objects, like this:
{
name: "name value",
modType: "report"
}
You could use a destructuring and map objects with short hand properties.
var dbJobs = [{ id: 123, name: "name value", data: { modType: "report", category: "value" } }],
result = dbJobs.map(({ name, data: { modType } }) => ({ name, modType }));
console.log(result);
So with Array.prototype.map() you can create a new structure based on its function's return value.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Think about the following:
const array = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
const result = array.map(e => {
return {
name: e.name,
modeType: e.data.modType
}
});
console.log(result);
Or the same with destructuring:
const array = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
const result = array.map(({name, data: {modType}}) => {
return {
name,
modType
}
});
console.log(result);
I hope that helps!
I believe this will do what you need:
let obj = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
let res = obj.map(item => {
return {
modType: item.data.modType,
category: item.data.category
}
});
console.log(res);
You can try this simple js code
arr = arr.map(item => {
const ob = {} // create temporary object
ob.name = item.name; // asign props from array object
ob.modType = item.data.modType; // asign props from array object
return ob // just return create object
})

Using filter() in combination with includes() to get partial matches

I have an array with objects I want to search through. The searchable array looks like this:
[
{ value: 0, label: 'john' },
{ value: 1, label: 'johnny' },
{ value: 2, label: 'peter' },
{ value: 3, label: 'peterson' }
]
I search through this using the Lodash filter method:
search = (text) => {
let results = _.filter(
this.props.options,
{ label: text }
);
}
This only shows the result that exactly matches the search query (text parameter). I need to make this work with partial matches. So if I insert j or johnny it should be able to find both 'John' and 'Johnny'.
I have tried:
search = (text) => {
let results = _.filter(
this.props.options =>
this.props.options.includes({ label: text })
);
}
But, no luck. No error and no results. How can I make this work?
Since you are using includes which is a part of ES6 standat, then I would solve this task with the ES6 Array.prototype.filter instead of lodash-filter:
let search = (list, text) =>
list.filter(i => i.label.toLowerCase().includes(text.toLowerCase()));
let list = [
{ value: 0, label: 'john' },
{ value: 1, label: 'johnny' },
{ value: 2, label: 'peter' },
{ value: 3, label: 'peterson' }
];
let result = search(list, 'j');
console.log(result); // [{value: 0, label: "john"}, {value: 1, label: "johnny"}]
Also, with .toLowerCase you may use "John" instead of "john".
String#includes accepts a string as a needle. If the the needle is not a string, it's converted to string, and it the case of an object it's [object Object].
You should get the value of label, and use the string's includes method:
const options = [
{ value: 0, label: 'john' },
{ value: 1, label: 'johnny' },
{ value: 2, label: 'peter' },
{ value: 3, label: 'peterson' }
];
const search = (text) => options.filter(({ label }) => label.includes(text));
const result = search('jo');
console.log(result);
That's not how you use String.prototype.includes. You should provide a string to it not an object. And you should provide a function that wraps the call to includes:
search = (text) => {
let results = _.filter(
this.props.options, // first parameter to _.filter is the array
option => option.label.includes(text) // the second parameter is a funtion that takes an option object and returns a boolean (wether the label of this option includes the text text or not)
);
}

How to get the value from an array which has key/value pair objects?

In the below array, I have objects with key/value pairs
var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
},
{
key: "second",
value: "Second Option"
}];
how to get the value based on key from options array?
For example, if the key is "select" it should return null,
if the key is "one" it should return "First Option".
ES6 has the find-function for arrays:
var val = options.find(function(o){ return o.key==="select" }).value;
And maybe wrap it in a function of your own to make it a bit more reusable:
function findValue(arr, key){
return arr.find(function(o){ return o.key===key }).value;
}
var val = findValue(options,"select");
I would argue this is the most semantically correct answer without modifying the original array, but you must have realized by now that there are many ways to skin this cat. (I like Zodiac Zubeda's answer because it's a simple for-loop so fast and backwards compatible and has the break that skips unnecessary iterations.)
You can search for the object you want from the array, then get the value of that object:
var value;
// Loop through the options array
for (var i = 0; i < options.length; i++) {
// If the key for this iteration's element is desired
if (options[i].key == "select") {
// Set the value to appropriately and exit the loop
value = options[i].value;
break;
}
}
This code makes "value" equal to the value you want, based on your key. If you want to determine the value multiple times, you can wrap the code in a function and return value. You'd probably also want to add a parameter for the desired key, and replace options[i].key == "select" with "options[i].key == <parameter name>".
Alternatively, you can structure your objects like so:
var options = {
"select": null,
"one": "First Option",
"second": "Second Option"
};
With this, you can access the value of a desired key like so:
options[<desired key>]
So, options["select"] would return null.
Using Array.prototype.filter (modern browsers and IE9+):
options.filter(function(opt) {
return opt.key === 'one';
})[0].value;
Or a one-liner using ES6 arrow notation:
options.filter(opt => opt.key === 'one')[0].value;
Reusable function, returning null if a match is not found:
function findValueByKey(opts, key) {
var match = opts.filter(function(opt) {
return opt.key === key;
});
return match[0] ? match[0].value : null;
}
JSFiddle: https://jsfiddle.net/02oawajt/3/
You have to brute force it...
function findValueForOption(key) {
for (i = 0; i < options.length; i++) {
if (options[i].key === key) {
return options[i].value;
}
}
return null; // Or do whatever you feel is appropriate when an unspecified key is requested...
}
Arraymap use to find key and value
var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
},
{
key: "second",
value: "Second Option"
}];
var run = options.map(function (item,index) {
var fullname = 'the key='+item.key+',and value='+item.value;
return fullname;
})
console.log(run);
var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
}, {
key: "second",
value: "Second Option"
}];
// output values of whatever you like
checkValue("select");
console.log("------------------------------");
checkValue("one");
console.log("------------------------------");
checkValue("second");
console.log("------------------------------");
function checkValue(val) {
for (var i = 0; i < options.length; i++) {
if(options[i].key == val){
console.log("VALUE IS: " + options[i].value);
}
}
}
Use forEach to loop through he json..
There are multiple ways of doing it.
This is one of the way
var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
},
{
key: "second",
value: "Second Option"
}];
options.forEach(function(item){
console.log(item.value)
})
DEMO
You may want to consider restructuring your data. It appears you took key, value literally:
If you structure your data like this:
var options = [
{
select: null
},
{
one: 'first option'
}
];
You can just call options.select to retrieve the value.
If you don't mind the dependency, you can turn your array into a proper Object using Lodash _.fromPairs:
pairs = options.map(o => [o.key, o.value])
// [["select", null], ["one", "First"], ["two", "Second"]]
_.fromPairs(pairs)
// { select: null, one: "First", second: "Second" }
I hope this will work for you
function getValue(keyName) {
if(!keyName) return ''
var value = _.find(options, function(obj){
if(obj.key === keyName) {
return true
}
})
if(value === undefined) return ''
return value.value
}
var a = getValue('one')
Check snippet for working example.
$(function(){
var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
},
{
key: "second",
value: "Second Option"
}];
function getValue(keyName) {
if(!keyName) return ''
var value = _.find(options, function(obj){
if(obj.key === keyName) {
return true
}
})
if(value === undefined) return ''
return value.value
}
var a = getValue('one')
console.log(a)
})
<script src="http://underscorejs.org/underscore.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
For older/ES3 environments:
function find(arr, key) {
for (var i = 0; i < arr.length; i += 1) {
if (arr[i].key === key) {
return arr[i].value;
}
}
}
For newer/ES5 environments:
function find(arr, key) {
return (arr.filter(function(item) { return item.key === key})[0] || {}).value;
}
This is one way of doing it. I have changed the structure of it like other suggested through program and then access the new Structure.
var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
},
{
key: "second",
value: "Second Option"
}];
function changeStructure(obj){
var newObj = {};
obj.forEach(function(val, index){
newObj[val['key']] = val['value'];
});
return newObj;
}
var newStructure = changeStructure(options);
New Structure :
{
one : "First Option"
second:"Second Option"
select:null
}
Now you can access it using key:
console.log(newStructure['select']); or console.log(newStructure.select)
JS Fiddle
You can use for..of loop.
var options = [{
key: "select",
value: null
}, {
key: "one",
value: "First Option"
}, {
key: "second",
value: "Second Option"
}];
let filter = (array, prop, res = void 0) => {
for (let {key, value} of array) prop === key && (res = value); return res
}
console.log(filter(options, "select"));
console.log(filter(options, "one"));
console.log(filter(options, "second"));

How to change index and value of array object in javascript

I have this Javascript Object as below format but I want to convert it to another format as below:
I've pass value form let data = $('#clientForm').serializeArray();
Original format
let data = $('#clientForm').serializeArray();
{ name="addr_types", value="RESID"}
Wanted Format
{addr_types:"RESID"}
Or another format
{"addr_types":"RESID"}
Assuming a valid object, you could just assign the wanted property with the given key/value pair.
var source = { name: "addr_types", value: "RESID" },
target = {};
target[source.name] = source.value;
console.log(target);
ES6 with computed property
var source = { name: "addr_types", value: "RESID" },
target = { [source.name]: source.value };
console.log(target);
Given that your original object is a correct one
var original = {
name: "addr_types",
value: "RESID"
};
console.log(original);
var newName = original.name;
var newValue = original.value;
var newObject = {};
newObject[newName] = newValue;
console.log(newObject);
You can simply do it using .map() function. bellow is the example.
var original = [{
name: "addr_types",
value: "Work"
},{
name: "village",
value: "Vang Tobang"
},{
name: "commune",
value: "Tang Krasang"
},{
name: "destric",
value: ""
},{
name: "city",
value: "Com Pong Thom"
},{
name: "country",
value: "combodia"
},
];
newArray = original.map(function(item){
return {[item.name]: item.value}
});
If your data container is not array then you can simply create as like bellow.
newArray = [original].map(function(item){
return {[item.name]: item.value}
});
Here is the jsfiddle link: https://jsfiddle.net/kzrngch6/

Categories