Assign object value as array in javascript - javascript

How to assign the value to array in object value? It may has multiple input coming in and expected the input appended to array.
Code:
var ob = {};
$.each( input, function( key, value ) {
var v = [];
ob[key] = v.push(value);
console.log( v );
console.log( "obj: " + ob );
console.log( key + ": " + value );
});
Input:
First input- {A: "34",B: "2"}
Second input- {A: "21",B: "11"}
Expected:
ob = {A: ["34","21"] ,B: ["2","11"]}

Hope this helps,
var ob = {};
$.each(input, function(key, value) {
if (!ob[key]) {
ob[key] = []; // Creates a new Array for the key, if no array is there
}
ob[key].push(value); // Pushes the value to the array of the particular key
});

Create a function and an object variable. Check if the key exist in that object. If it does not exist they create the key and push the values
let input1 = {
A: "34",
B: "2"
}
let input2 = {
A: "21",
B: "11"
}
// a object which will hold the key and value
let finalObj = {};
// create a function which will be called o add key an value property to object
function createObj(obj) {
// iterate the object
for (let keys in obj) {
// check if final object has the relevent key
if (finalObj.hasOwnProperty(keys)) {
// if it has that key then push the value according to the key
finalObj[keys].push(obj[keys])
} else {
finalObj[keys] = [obj[keys]]
}
}
}
createObj(input1)
createObj(input2)
console.log(finalObj)

The problem is v empties on each iteration, because of this line:
var v = [];
Try doing this instead:
$.each(input, (key, val) => {
if (ob[key]) {
ob[key].push(val);
} else {
ob[key] = [val];
}
});

Related

a function to create and add to an object

Complete a function that takes in three parameters, an object, and a string (which will represent a key), and a value. The function needs to add a property to the inputted object. The property's key is a string, and the value of this property should be the inputted value. The function should return the inputted object.
function addProperty(obj, key, value) {
// your code here
var obj = {};
obj[key] = value;
return obj;
}
As this function stands it takes in one key and one value. I need it to let me add as many keys and values as I want. Please help.
1) Passing array of key and value
function addProperty(obj, keyArr, valueArr) {
keyArr.forEach((k, i) => {
obj[k] = valueArr[i];
});
return obj;
}
const keys = ["A", "B", "C"];
const values = ["value of A", "value of A", "value of A"];
let obj = {};
obj = addProperty(obj, keys, values);
console.log(obj);
2) Iterating over array key and calling the function as many times as length of the key array
function addProperty(obj, key, value) {
obj[key] = value;
return obj;
}
const keys = ["A", "B", "C"];
const values = ["value of A", "value of A", "value of A"];
let obj = {};
keys.forEach((k, i) => {
obj = addProperty(obj, k, values[i]);
});
console.log(obj);
try this
function addProperty(obj, keys_and_values) {
// your code here
var obj = {}
for (let key in keys_and_values) {
obj[key] = keys_and_values[key]
}
return obj
}
console.log(addProperty({}, {"name": "hi", "age": 69}))
output
{
age: 69,
name: "hi"
}
You'll have to remove var obj = {} in your addProperty function. I think you want to pass the object which should be expanded, right?
var obj = {};
var data = [{
key: "KEYA",
value: "VALUEA"
},
{
key: "KEYB",
value: "VALUEB"
}
];
var data2 = [{
key: "KEYC",
value: "VALUEC"
}
];
//Add key/value pairs to obj
console.log(addProperty(obj, data));
//Add another key/value pair to obj
console.log(addProperty(obj, data2));
function addProperty(obj, data) {
for (var key in data) {
obj[data[key].key] = data[key].value;
}
return obj;
}
I don't know why everyone were over explaining the question here-
We need to achieve 3 things here-
Function needs to add a property to the inputted object.
The value of property should be the inputted value.
function should return the inputted object.
function addProperty(obj, key, value) {
obj[key] = value ;
return obj ;
}

manipulate the object value without knowing its key

I have an object obj and I want to manipulate it's value, but I don't want to write the value hard-coded something like below, is there any better alternative to this below approach
let obj = {a:{x:0}, b:{y:0}};
obj.a[Object.keys(obj.a)[0]] = 1;
console.log(obj);
I suppose you want to loop through them and have different values for x, y or whatever the key is
let obj = {
a: {
x: 0
},
b: {
y: 0
}
};
keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
key2 = Object.keys(obj[keys[i]])[0];
// instead of some_value inject an array of values
obj[keys[i]][key2] = 'some_value';
}
console.log(obj);
I have created a generic function where you can set the value of key without knowing the property names of inside object.
You can call the function with required key and value and get the desired result.
let obj = {a:{x:0}, b:{y:0}};
function assignValue(key, value) {
obj[key][Object.keys(obj[key])] = value;
}
assignValue('a', 1)
console.log(obj)
let objMultipleInnerKeys = {a:{x:0, z:2}, b:{y:0}};
function assignValueMultipleInnerKeys(key, innerKey, value) {
objMultipleInnerKeys[key][innerKey] = value;
}
assignValueMultipleInnerKeys('a', 'x', 1)
console.log(objMultipleInnerKeys)

How to get key and value of object in javascript?

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)))

Splitting dots into separate objects javascript

I have an object like this:
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1}
I want to change it into an object like this:
{
"prop": {
"health": 1,
"cost":1,
"time":1
}
}
Here's my code:
_.each(data, function (value, key) {
var split = key.split('.')
if (split.length > 1) {
data[split[0]] = data[split[0]] || {}
data[split[0]][split[1]] = value
delete data[key]
}
})
But this only works for 1 level of nesting. How would you write it to ensure it works for as deeply nested properties as you need?
You can use a combination of _.transform and _.set, for example
data = _.transform(data, function(transformed, val, key) {
_.set(transformed, key, val);
});
Results in
{"prop":{"health":1,"cost":1,"time":1}}
Without a library it would be something like this:
(function(){
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1, "prop.test.fun" : 1, "prop.test.sun" : 1};
var obj = {}; //will hold the object all parsed out
Object.keys(data).forEach( function (key) { //loop through the keys in the object
var val = data[key]; //grab the value of this key
var step = obj; //reference the object that holds the values
key.split(".").forEach(function(part, index, arr){ //split the parts and loop
if(index===arr.length-1){ //If we are at the last index, than we set the value
step[part] = val;
} else if(step[part]===undefined) { //If we have not seen this key before, create an object
step[part] = {};
}
step = step[part]; //Step up the object we are referencing
});
} );
console.log(obj);
}());
Or the double reduce loop
(function(){
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1, "prop.test.fun" : 1, "prop.test.sun" : 1};
var result = Object.keys(data).reduce( function (obj, key) { //loop through the keys in the object
var val = data[key]; //grab the value of this key
key.split(".").reduce(function(step, part, index, arr){ //split the parts and loop
if(index===arr.length-1){ //If we are at the last index, than we set the value
step[part] = val;
} else if(step[part]===undefined) { //If we have not seen this key before, create an object
step[part] = {};
}
return step[part]; //Step up the object we are referencing
}, obj);
return obj;
}, {});
console.log(result);
}());
Depending on a number of factors (e.g. if the original object always has keys you want to delete, etc.) you may be able to use _.set:
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1};
_.each(data, function (value, key) {
delete data[key];
_.set(data, key, value);
});
_.set will create the path if it doesn't exist. The above results in:
{"prop":{"health":1,"cost":1,"time":1}}
And {"prop.health": 1, "prop.cost.food":1, "prop.time":1} will result in:
{"prop":{"health":1,"cost":{"food":1},"time":1}}

Dynamically create angular object with key, value from angular.forEach()

if ($scope.data) {
$formData = [];
angular.forEach($scope.data, function(value, key){
console.log(key); // o/p: 'fruitname'
var k = key;
var value = value || 'Not Available';
console.log(value); // o/p: 'apple'
var parts = {k : value};
console.log(parts); // o/p: Object {k: "apple"}
$formData.push(parts);
});
}
Why i cannot able to populate key, while creating parts object. or how can i do the same.
What you need to do is parts[k] = value;
Actually when you assign parts = { k : value }; , This goes something like this :
parts["k"] = value;
So you see instead of taking the value of k, it takes k as string and assign a value to this string as key field.
it works when i try to do like this.
if ($scope.data) {
$formData = [];
angular.forEach($scope.data, function(value, key){
console.log(key); // o/p: 'fruitname'
var value = value || 'Not Available';
console.log(value); // o/p: 'apple'
var parts = {};
parts[key] = value;
console.log(parts); // o/p: Object {"fruitname": "apple"}
$formData.push(parts);
});
}

Categories

Resources