1

I want to create data structure like that.

Var ans =[{"b":[1,2]},{"g":[100,2]}]

I want to create a new object within list if key not exists in list ans. Else if key exists in one object of ans list then I want to add new values into the object of ans list

For Example:

Example 1) new data c:{2000}

then

Var ans =[{"b":[1,2]},{"g":[100,2]},{c:[2000]}]

Example 2) new data g:{50}

then

Var ans =[{"b":[1,2]},{"g":[100,2,500]},{c:[2000]}]

I am a beginner in node js, understand array, object concept, but not getting exact logic! Thanks!

10
  • what is {2000} (in javascript)? Commented Mar 7, 2017 at 14:46
  • c:{2000} is not a valid declaration in javascript Commented Mar 7, 2017 at 14:49
  • 1
    You can do var obj = ans.filter(x=>!!x[searchKey])[0]; obj ? obj[searchKey].push(value) : ans.push({searchKey: [value] }) Commented Mar 7, 2017 at 14:54
  • Thanks! @rajesh. Finnaly i got it using your solution Commented Mar 7, 2017 at 15:22
  • @Rajesh One problem i noticed in your solution is, when i hold search key in variable then i pass but it is treating variable name as search key.. var xyz="testkey" then if pass xyz in place of search key , so it is search for key 'xyz' instead of 'testkey' Commented Mar 7, 2017 at 16:06

3 Answers 3

2

You can try following:

Logic

  • Filter array based on key
  • Check if object with mentioned key exists or not.
  • If yes, push value to this array.
  • If not, create a dummy object and push this object to original array.

Correction, when you do .push({key: value}), key will be considered as string.

Alternates

  1. If you are using ES6, .push({ [key] : value })
  2. Create a dummy object var o = {}. Set key and value to it o[key] = value and push this object.

Optimisations

  • Instead of setting value like obj[key] = value, since we will be operating on arrays, try obj[key] = [].concat(value). This will enable you to pass value as number or array of values.
  • Instead of checking the existence of value in .filter, try Array.isArray to check if value exists and is of type array.

Custom function

function checkAndPush(array, key, value) {
  var filteredList = array.filter(function(o) {
    return Array.isArray(o[key]);
  });

  filteredList.length > 0 ? filteredList[0][key].push(value) : array.push({
    [key]: [].concat(value)
  });
  return array;
}

var ans =[{"b":[1,2]},{"g":[100,2]}]

console.log(checkAndPush(ans, "c", [2,3]))
console.log(checkAndPush(ans, "c", 4));

Prototype function

Array.prototype.checkAndPush = function(key, value) {
  var filteredList = this.filter(function(o) {
    return Array.isArray(o[key]);
  });
  var dummy = {}
  dummy[key] = [].concat(value)

  filteredList.length > 0 ? filteredList[0][key].push(value) : this.push(dummy);
  //  or ES6: this.push({ [key]: [].concat(value) })
  return this;
}

var ans =[{"b":[1,2]},{"g":[100,2]}]

console.log(ans.checkAndPush("c", [2,3]))
console.log(ans.checkAndPush("c", 4));

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you soo much for help. I used my own solution, but your solution help me lot to understand many thing in node js. Thanks :)
2

If you are dealing with objects as your values

ans[key] = ans[key] || []
ans[key].push(value)

Note, this works because your values will be an array. If they could be primatives then you would use hasOwnProperty to check.

if (ans.hasOwnProperty(key)) {
  // Add this to your key somehow
} else {
  // initialize the key with your value
}

2 Comments

if ans[key] is a falsy value ? better to use key in ans
@PranavCBalan can you think of any scenario where the list value would be falsey here in this scenario where he is use the key to reference an array of answers?
0

Node.js is nothing but a library built on javascript. You can do anything using javascript type of progmming. However push and pop method should be able to help you to deal with nodejs array. ans[key].push(value)

2 Comments

Javascript is a language, not a technology. Node is V8 + LibUV + some other C++ bindings. That said, maybe a code example would help.
guys this solution is working for me only if pass key directly var obj = ans.filter(x=>!!x[searchKey])[0]; obj ? obj[searchKey].push(value) : ans.push({searchKey: [value] }) , if i hold key in variable then it is not working.. for exam var xyz="testkey" then if pass xyz in place of search key , so it is search for key 'xyz' instead of 'testkey'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.