I have an object that contains key pair values of objects that are in array form:
let obj = {};
let joinedData;
obj["key1"] = ["val1", "val2"];
obj["key2"] = ["val3", "val4"];
I want to join all the values together as a string:
for (const [key, values] of Object.entries(obj)) {
joinedData = `${values.join(",")}`;
}
The expected result is "val1,val2,val3,val4"
But joinedData is empty.
I suspect that it's because the values are objects and not array (when I use typeof).
How to get the expected result in this case?
You can use Object.values and flat:
let obj = { key1: ["val1", "val2"], key2: ["val3", "val4"] };
let joinedData = Object.values(obj).flat().join();
console.log(joinedData);
If you have some arrays that contain empty strings, then you may want to filter those out, with filter(Boolean):
let obj = { key1: ["val1", "val2"], key2: ["val3", "val4"], key3: [""], key4: [""] };
let joinedData = Object.values(obj).flat().filter(Boolean).join();
console.log(joinedData);
You can use this - joinedData = Object.values(obj).flat().join(',')
First join the both list in any single list like
var newlist = obj["key1"].join(obj["key2"]);
After join the values by comma seprated
joinedData = newlist.join(',');
get all values from obj using let objValues = Object.values(obj);
now you can a for loop over obj values and append both elms like for(const v of objValues) { joinedData.push(v[0]); joinedData.push(v[1]); } or nested for loop works too
let obj = {};
let joinedData = [];
obj["key1"] = ["val1", "val2"];
obj["key2"] = ["val3", "val4"];
let objValues = Object.values(obj); //List of tuples ?
for (const v of objValues) {
joinedData += v[0] + ',';
joinedData += v[1] + ' ';
}
console.log(joinedData)
if you were to write out your object literally, you would have:
obj = {key1 : ["val1", "val2"], key2 : ["val3", "val4"]}
Array.join() concatenates array elements into a string. Array elements that are arrays themselves cannot be directly concatenated into a string. Try:
let str = '';
for(let i of Object.values(obj)) { // retrieve each value (which is an array)
str += i.join(', ') + ', '; // join elements of each array & concatenate
} // extra comma between each joined array
console.log(str)
You still need to strip the extra comma off the end
Related
I have a following string:
var str = "name=test1^assigned_to=12345678901112131415161718991234^business_service=99945678901112131415161718991211^EQ";
var obj = { name: 'test1',
assigned_to: '12345678901112131415161718991234',
business_service: '99945678901112131415161718991211'
};
and would like to create object of specific keys and values from that string as is in my example, has anyone achieved similar thing? How?
let str = "name=test1^assigned_to=12345678901112131415161718991234^business_service=99945678901112131415161718991211^EQ";
let obj = {}
str.split('^').forEach(e => {
let x = e.split('=');
if (x[1])
obj[x[0]] = x[1]
});
console.log(obj);
You can remove if (x[1]) condition;
I have tried to retrieve all the values of an plain object which returns an array separated with comma since I am using map().
var obj = { 1: 'Banana', 2: 'Orange'};
var values = Object.keys(obj).map(function(e) {
return obj[e]
}) //returns ['Banana','Orange']
Where as I need all the values and keys as string separated by comma from below object array without using Object.values() and Object.keys
input: var items = [{1:"Banana"}, {2:"Orange"}, {3:"Apple"}]
output 1: "1,2,3" ---> keys
output 2: "Banana,Orange,Apple" --> values
Problem is when the objects are inside an array I am not getting any idea how to retrieve keys and object values separately.
Kindly help!
You can use array reduce & join
Inside reduce callback use for..in to iterate the object. [[],[]] is the accumulator & in the first array keys will be collected and in second array values will be collected.
Inside the for..in push the keys & values from each object.
Once done use join with delimiter , to create the string
var items = [{
1: "Banana"
}, {
2: "Orange"
}, {
3: "Apple"
}]
let vals = items.reduce(function(acc, curr) {
for (let keys in curr) {
acc[0].push(keys);
acc[1].push(curr[keys])
}
return acc;
}, [
[],
[]
]);
console.log(vals[0].join(','), vals[1].join(','))
You can iterate over the array and in a nested for loop iterate over the object:
var items = [{1:"Banana"}, {2:"Orange"}, {3:"Apple"}];
let keys = [];
let values = [];
for (let element of items){
for (let i in element){
keys.push(i);
values.push(element[i]);
}
}
keys = keys.join(",");
values = values.join(",");
console.log(keys);
console.log(values);
Using for ... in
const items = [{
1: "Banana"
}, {
2: "Orange"
}, {
3: "Apple"
}];
let keys = '';
let values = '';
items.forEach((x) => {
for (let y in x) {
keys = `${keys}${keys.length ? ',' : ''}${y}`;
values = `${values}${values.length ? ',' : ''}${x[y]}`;
}
});
console.log(keys);
console.log(values);
Using Object.keys() and Array.reduce
const items = [{
1: "Banana"
}, {
2: "Orange"
}, {
3: "Apple"
}];
const rets = items.reduce((tmp, x) => {
Object.keys(x).forEach((y) => {
tmp.keys = `${tmp.keys}${tmp.keys.length ? ',' : ''}${y}`;
tmp.values = `${tmp.values}${tmp.values.length ? ',' : ''}${y}`;
});
return tmp;
}, {
keys: [],
values: [],
});
console.log(rets);
With the for..in and for..of functions
const items = [{1:"Banana"}, {2:"Orange"}, {3:"Apple"}];
let keys = [];
let values = [];
for(let item of items){
for(let key in item){
keys.push(key);
values.push(item[key]);
}
}
// keys == [1, 2, 3]
// values == [Banana, Orange, Apple]
After this you can use the join function
console.log(keys.join()); // Output : "1,2,3"
console.log(values.join()); // Output : "Orange,Banana,Apple"
I have an array:
let arr = ["a=1", "b=22", "c=11"];
And I want to split the string inside array so it becomes an object later, which will look like:
{a: 1, b: 22, c: 11}
Can I somehow do that
You could split the string an map new objects. Later assign all objects to a single object.
var array = ["a=1", "b=22", "c=11"],
object = Object.assign(
...array.map(s => ((k, v) => ({ [k]: +v }))(...s.split('=')))
);
console.log(object);
you can use array.forEach, so you wont be creating an array instead you will iterate through the array, and you can take each item and split so it will create an array
like item = ["a", "1"], you can assign the key as a to the object which is the first index and value is second index,The value is string so you can convert to number and return it.
let arr = ["a=1", "b=22", "c=11"];
var obj = {}
arr.forEach(o => {
var item = o.split("=");
return obj[item[0]] = Number(item[1])
})
console.log("required obj", obj)
You can use array#map with Object.assign() to create your object. string#split each word on = and generate the object.
let arr = ["a=1", "b=22", "c=11"],
result = Object.assign(...arr.map(word => {
let [key,value] = word.split('=');
return {[key] : +value};
}));
console.log(result);
You can also use array#reduce.
let arr = ["a=1", "b=22", "c=11"],
result = arr.reduce((r,word) => {
let [key,value] = word.split('=');
r[key] = +value;
return r;
}, {});
console.log(result);
Here, try this
let arr = ["a=1", "b=22", "c=11"];
const obj = {}
arr.forEach(i => {
const splitted = i.split('=')
obj[splitted[0]] = splitted[1]
} )
console.log(obj)
I have object as var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}] . I want to get key and value this sample
PRODUCT_ID is P01
M01 is 1
M02 is 2
M03 is null
I try with as follow
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + " is " + obj[key]);
}
}
It't not working , it's show wrong with format.
0 is [
1 is {
2 is "
3 is P
4 is R
5 is O
6 is D
...etc
I using javascript to this. If maybe can convert to json and show this .
My guess is that the object you receive is a string not an actual object or array. This is why with your code, it gives the output.
To convert to an actual JS object use JSON.parse() and it will return an array as expected.
For instance,
const myArray = JSON.parse(obj);
myArray.forEach(x => Object.entries(x).map(([key, value]) => console.log(`${key} is ${value}\n`)))
Observation :
for...in statement iterates over the enumerable properties of an object. Hence, As per the code in OP :
var obj = [{
"PRODUCT_ID": "P01",
"M01": 1,
"M02": 2,
"M03": null
}];
for (var key in obj) {
console.log(key); // 0
}
Try this :
var obj = [{
"PRODUCT_ID": "P01",
"M01": 1,
"M02": 2,
"M03": null
}];
for (var i of obj) {
for (var j in Object.keys(i)) {
console.log(Object.keys(i)[j] + " is " + i[Object.keys(i)[j]]);
}
}
the problem is you are querying obj, while the actual obj is obj[0]. obj is an array with 1 element. try this
var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}];
for (var key in obj[0]) {
if (obj[0].hasOwnProperty(key)) {
console.log(key + " is " + obj[0][key]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
use Object.keys() method to access the keys in your object and then simply concatenate the key with its value.
this is not the most elegant solution, but it will help you understand.
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]' //string
obj = JSON.parse(obj);
console.log(Object.keys(obj[0])) //so that you can see what this does
obj.forEach(object => {
Object.keys(object).forEach(key => {
$("#values").append($("<p>"+key +" is "+ object[key]+"</p>"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="values">
</div>
The thing here is that you are treating an array like an object. Change your code for:
for(x=0;x <obj.length;x++){
// Here you have each object of your array.
var json = obj[x];
var arrayOfKeys = Object.keys (json);
//other code.
}
See Object.entries(), Array.prototype.map(), and Template Literals for more info.
// Input.
const input = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]
// Output.
input.map(x => Object.entries(x).map(([key, value]) => console.log(`${key} is ${value}\n`)))
You can use Object.entries() like:
const jsonString = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]'
// parse your json string first
const arr = JSON.parse( jsonString );
// Get the object from the array
const obj = arr[0] || {};
for (const [key, value] of Object.entries(obj)) {
console.log(key + ' is '+value);
}
Your code almost correct. But as you have data array not object you need to loop trough the object to achieve desire output.
Guessing OP has:
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]';
for (var key in obj) {
console.log(key + " is " + obj[key]);
}
//var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]';
obj = JSON.parse(obj);
for (var key in obj) {
for (var k in obj[key]){
console.log(k + " is " + obj[key][k]);
}
}
Alternative:
//var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]';
obj = JSON.parse(obj);
obj.map(e => Object.entries(e).map(([k, v]) => console.log(k, "is", v)))
I have a Javascript object like
Object = { "ratio1" : "12+45*36",
"ratio2" : "34+45*16",
"ratio3" : "17+25"}
I am trying to split the values like the values before + in one array and values after + in one array . so the output should be like
Array1= ["12" , "34" , "17"]
Array2 = ["45" , "36" , "45","16","25"].
To perform this I am iterating through the keys and getting the values first then I am again iterating through the values array I am splitting it using
ratioArray.split("+");
This gave me [[" 12" , "45*36"], [" 34", "45*16"], [" 17", "25"]]
Now again I have iterate through all the three arrays and split using second delimiter. Is there any efficient way to perform this so that I can reduce these many iterations
const ratios = {
"ratio1" : "12+45*36",
"ratio2" : "34+45*16",
"ratio3" : "17+25"
}
const nums = Object.keys(ratios)
.map(key => ratios[key]
.replace(/[+*]/g, '|')
.split('|')
)
const [ array1, array2, array3 ] = nums
document.querySelector('pre').innerText =
`array1 === [${array1}]\n` +
`array2 === [${array2}]\n` +
`array2 === [${array3}]\n`
<pre />
var Object = {
"ratio1": "12+45*36",
"ratio2": "34+45*16",
"ratio3": "17+25"
}
var Array1 = [],
Array2 = [],
temp;
for (var key in Object) {
temp = Object[key].split('+');
Array1.push(temp[0])
temp = temp[1].split('*')
for(var i = 0; i < temp.length; i++){
Array2.push(temp[i])
}
}
console.log('Array1:['+Array1[0]+','+Array1[1]+','+Array1[2]+']')
console.log('Array2:['+Array2[0]+','+Array2[1]+','+Array2[2]+','+Array2[3]+','+Array2[4]+']')
You can do something like this.
object = {
"ratio1": "12+45*36",
"ratio2": "34+45*16",
"ratio3": "17+25"
}
var array1 = [],
array2 = [];
for (var key in object) {
var _o = object[key].split("+");
array1.push(_o[0]);
_o[1].split("*").forEach(function(num) {
array2.push(num);
})
};
console.log("array 1", array1);
console.log("array 2", array2)